Step 1
Create an interface.
Strategy.java
public interface Strategy { public int doOperation(int num1, int num2); }
Step 2
Create concrete classes implementing the same interface.
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
interface Strategy { public double getValue(double price); } class Add implements Strategy{ @Override public double getValue(double price) { return price + 1.5; } } class Substract implements Strategy{ @Override public double getValue(double price) { return price - 1.5; } } import java.util.ArrayList; import java.util.List; class Context { private List<Double> list; private Strategy strategy; public Context(Strategy strategy) { this.list = new ArrayList(); this.strategy = strategy; } public void executeStrategy(double price, int Quantity) { list.add(strategy.getValue(price*Quantity)); } public void displayPayment(){ double sum =0; for(Double d : list){ sum += d; } System.out.println("Total due: "+sum); list.clear(); } } class Program { public static void main(String[] args) { Context c = new Context(new Add()); c.executeStrategy(9.5, 2); c.displayPayment(); Context c1 = new Context(new Substract()); c1.executeStrategy(9.5, 2); c1.displayPayment(); } }Output:
Total due: 20.5
Total due: 17.5
0 nhận xét:
Post a Comment