Minggu, 27 November 2016

Design Patterns - Strategy Pattern

dalam pola strategi, perilaku kelas atau algoritma dapat diubah berdasarkan berjalannya waktu. 
dalam pola strategi, objek yang kita buat mewakili berbagai strategi dan objek konteks yg perilakunya bervariasi sesuai objek strateginya. objek strategi perubahan algoritma mengeksekusi objek konteks.

IMPLEMENTASI


Step 1 : create an interface (strategy.java)
public interface Strategy {
   public int doOperation(int num1, int num2);
}
Step 2 : create concrete classes implementing  (operationadd.java)
public class OperationAdd implements Strategy{
   @Override
   public int doOperation(int num1, int num2) {
      return num1 + num2;
   }
}
(operationsubstract.java)
public class OperationSubstract implements Strategy{
   @Override
   public int doOperation(int num1, int num2) {
      return num1 - num2;
   }
}
(operationmultiply.java)
public class OperationMultiply implements Strategy{
   @Override
   public int doOperation(int num1, int num2) {
      return num1 * num2;
   }
}
Step 3 : Create Context Class (context.java)
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);
   }
}
Step 4 : Use the Context to see change in behaviour when it changes its Strategy(strategypatterndemo.java)
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));
   }
}
step 5 : verify the output
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50

Tidak ada komentar:

Posting Komentar