Saturday 1 October 2022

 Design Pattern: Strategy 

a)Strategy Design Pattern:

In strategy design pattern, we can change class behaviour or algorithm on fly.

E.g.: We create interface which accepts two numbers. Now, we can call either of the concrete class which is implementing logic for this interface and thus change the behavior of final calling class.


//Create an interface

a) public interface Numbers {

     int operation(int a, int b);

}

//Create concrete classes which will implement above interface

b) public class AddNumber implement Numbers {

  @Override

   public int operation(int a, intb){

   int c = a+b;

return c;

}

}

c) public class SubtractNumber implement Numbers {

@Override

   public int operation(int a, intb){

   int c = a-b;

return c;

}

}

//Create intermediate class which implements the strategy classes above

d) public class Context {

private Numbers numbers;


//this is parametrized class instance of Context

public class Context(Numbers numbers){

this.numbers = numbers;

}

public int mathOperation(int c, int d){

   numbers.operation(c,d)

}

}

//Now implement strategy class

e) public class StrategyDemo {

  

        public void strategyMethod(){

Context addContext = new Context(new AddNumber());

addContext.mathOperation(7,8); 

//output here is 15 because it call operation method from AddNumber class

Context subContext = new Context(new SubtractNumber());

subContext.mathOperation(4,2);

// output is 2 because it will call operation method from SubstractNumber class

}

}

//If you see here, we can either call the SubtractNumber or AddNumber class and thus change the final outcome of the strategyMethod()


No comments:

Post a Comment