Skip to content

Commit

Permalink
Merge pull request #460 from AdolfCarr/behavioral/strategy
Browse files Browse the repository at this point in the history
Implement Arithmetic Operations Using Strategy Pattern
  • Loading branch information
ZoranPandovski authored Dec 13, 2024
2 parents f927060 + 7d5ed4c commit db0dcf0
Show file tree
Hide file tree
Showing 10 changed files with 155 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Strategy Pattern

This design pattern is especially powerful in scenarios where multiple algorithms need to coexist and be interchangeable at runtime without modifying the core business logic.

## Strategy Pattern for Arithmetic Operations
> This example of the Strategy Pattern demonstrates how algorithms for addition, subtraction, and multiplication are encapsulated in separate strategy classes. The CalculatorContext class delegates the execution to a Strategy instance via polymorphism, enabling dynamic behavior selection at runtime. This approach simplifies adding new algorithms and keeps the design flexible, scalable, and maintainable..
<p align="center">
<img src="images/strategy_pattern.png" width="878" height="582" alt="Strategy pattern - Diagram of classes, this diagram was generated with https://app.diagrams.net/">
</p>

<p align="center">

<p align="center">
<em>Fig 1: Strategy pattern - Diagram of classes, this diagram was generated with https://app.diagrams.net/</em>
</p>

**RelationShips**

**1. Interface Implementation:**

- AdditionStrategy, SubstractionStrategy, and MultiplicationStrategy implement the Strategy interface, showcasing a polymorphic relationship.

**2. Aggregation:**

- CalculatorContext has an aggregation relationship with the Strategy interface because it holds a reference to a Strategy instance but does not own it permanently.

**3. Dependency:**

- The CalculatorClient depends on CalculatorContext and concrete strategies (AdditionStrategy, SubstractionStrategy, and MultiplicationStrategy) to fulfill its operations.

**Key Points**

**1. Polymorphism via the Interface:**

- The `Strategy` interface defines the `execute` method that all concrete strategy classes (`AdditionStrategy`, `SubstractionStrategy`, `MultiplicationStrategy`) implement.
- Since `strategy` is declared as type `Strategy` in the `CalculatorContext` class, it can hold a reference to any object that implements the `Strategy` interface.
- This allows the `executeStrategy` method to call the `execute` method on the `strategy` instance without knowing its exact type, relying purely on the interface.

**2. Decoupling the CalculatorContext from the Concrete Strategies:**

- The `executeStrategy` method doesn't need to know which specific algorithm (e.g., addition, subtraction, or multiplication) is being executed.
- This responsibility is shifted to the `strategy` instance, which is set dynamically at runtime via the `setStrategy` method.

**3. Flexibility and Scalability:**

- Flexibility: You can change the behavior of the `executeStrategy` method at runtime by providing a different strategy instance.
- Scalability: Adding new strategies (e.g., division or exponentiation) is straightforward. You simply create a new class implementing the `Strategy` interface without modifying the existing code in the `CalculatorContext` or `executeStrategy` method. This adheres to the **Open/Closed Principle** of SOLID design principles.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
14 changes: 14 additions & 0 deletions Behavioral/Strategy/java/strategy_arithmetical_operations/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany</groupId>
<artifactId>strategy_arithmetical_operations</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>18</maven.compiler.source>
<maven.compiler.target>18</maven.compiler.target>
<exec.mainClass>com.mycompany.strategy_arithmetical_operations.Strategy_arithmetical_operations</exec.mainClass>
</properties>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.mycompany.strategy_arithmetical_operations;

// Client: Demonstrates the use of the Strategy pattern
public class CalculatorClient {
public static void calculatorClient(){
CalculatorContext calculator = new CalculatorContext();

int firstNumber = 10;
int secondNumber = 5;

// Perform Addition
calculator.setStrategy(new ConcreteStrategyAdd());
System.out.println("Addition: " + calculator.executeStrategy(firstNumber, secondNumber));

// Perform Subtraction
calculator.setStrategy(new ConcreteStrategySubstract());
System.out.println("Subtraction: " + calculator.executeStrategy(firstNumber, secondNumber));

// Perform Multiplication
calculator.setStrategy(new ConcreteStrategyMultiply());
System.out.println("Multiplication: " + calculator.executeStrategy(firstNumber, secondNumber));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.mycompany.strategy_arithmetical_operations;

// Context: Represents the arithmetic calculator
public class CalculatorContext {

private Strategy strategy;

// Set the strategy dynamically
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}

// Execute the selected strategy
public int executeStrategy(int a, int b) {
if (strategy == null) {
throw new IllegalStateException("Strategy not set.");
}
return strategy.execute(a, b);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.mycompany.strategy_arithmetical_operations;

// Concrete Strategy for Addition
public class ConcreteStrategyAdd implements Strategy {

@Override
public int execute(int a, int b) {
return a + b;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.mycompany.strategy_arithmetical_operations;

// Concrete Strategy for Multiplication
public class ConcreteStrategyMultiply implements Strategy {

@Override
public int execute(int a, int b) {
return a * b;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.mycompany.strategy_arithmetical_operations;

// Concrete Strategy for Substraction
public class ConcreteStrategySubstract implements Strategy {

@Override
public int execute(int a, int b) {
return a - b;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.mycompany.strategy_arithmetical_operations;

// Strategy Interface: Defines the common behavior for all strategies
public interface Strategy {

int execute(int a, int b);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.mycompany.strategy_arithmetical_operations;

public class Strategy_arithmetical_operations {

public static void main(String[] args) {

CalculatorClient.calculatorClient();

}
}

0 comments on commit db0dcf0

Please sign in to comment.