Strategyパターンはある条件をきっかけに中の処理を切り替えることができるパターンです。
Contextの中のStrategyを置き換えることで動作が切り替わります。
package com.example.strategy;
public interface Strategy {
public void methodA();
public void methodB();
}
package com.example.strategy;
public class ConcreteStrategy1 implements Strategy {
public void methodA() {
}
public void methodB() {
}
}
package com.example.strategy;
public class ConcreteStrategy2 implements Strategy{
public void methodA() {
}
public void methodB() {
}
}
package com.example.strategy;
public class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void methodA() {
strategy.methodA();
}
public void methodB() {
strategy.methodB();
}
}
package com.example.strategy;
public class Main {
public static void main(String[] args) {
Context context1 = new Context(new ConcreteStrategy1());
Context context2 = new Context(new ConcreteStrategy2());
context1.methodA();
context1.methodB();
context2.methodA();
context2.methodB();
}
}