Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to understand Strategy pattern

I am following an example of strategy pattern from here

Everything in the tutorial is clear but this:

public class Context {
   private Strategy strategy;

   public Context(Strategy strategy){
      this.strategy = strategy;
   }

   public int executeStrategy(int num1, int num2){
      return strategy.doOperation(num1, num2);
   }
}

So the Context class expects a Strategy argument in its constructor.

The definition of Strategy is:

public interface Strategy {
   public int doOperation(int num1, int num2);
}

The above being an interface, the Context Class expects an object of type Strategy. In the StrategyPatternDemo class we do:

public class StrategyPatternDemo {
   public static void main(String[] args) {
      Context context = new Context(new OperationAdd());        
      System.out.println("10 + 5 = " + context.executeStrategy(10, 5));

      context = new Context(new OperationSubstract());      
      System.out.println("10 - 5 = " + context.executeStrategy(10, 5));

      context = new Context(new OperationMultiply());       
      System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
   }
}

I am utterly confused as we cant init an interface according to the definition:

An interface is different from a class in several ways, including:

You cannot instantiate an interface.

How exactly is this Context context = new Context(new OperationAdd()); sent as an argument to public Context(Strategy strategy){ this.strategy = strategy; }

like image 820
User3 Avatar asked Oct 06 '15 07:10

User3


2 Answers

The classes OperationAdd, OperationSubstract and OperationMultiply all implement the interface Strategy. Therefore instances of those classes can be passed into the constructor of Context which expects an object of type Strategy.

As OperationAdd, OperationSubstract and OperationMultiply implement the interface Strategy, they are all of that type.

like image 198
hotzst Avatar answered Nov 01 '22 00:11

hotzst


You are probably missing these lines, at the beginning of the example:

public class OperationSubstract implements Strategy{
    @Override
    public int doOperation(int num1, int num2) {
        return num1 - num2;
    }
}
... // etc.

Here you can see that there are some "operation" classes that implement the Strategy interface. A class that implements an interface is basically an "actual instance" of that interface.

You may think this way, if it's clearer to you:

  • an Interface is a representation of a "behaviour";
  • a class that implements that interface is something that can "behave like the interface states";
  • a method that accept an "interface" as an argument is a method that simply wants an object that "can behave" like the interface states, and it doesn't mind of the actual class of the object that is passed as an argument.
like image 38
javatutorial Avatar answered Oct 31 '22 23:10

javatutorial