mardi 6 octobre 2015

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; }

Aucun commentaire:

Enregistrer un commentaire