1.介面寫個方法,然後寫類別實作
2.寫個類別,將1的介面為他的 field,並寫一支方法,裡面寫呼叫介面裡的方法
※
public interface Strategy {
void method();
}
--------------------
public class StrategySon1 implements Strategy {
@Override
public void method() {
System.out.println("StraterySon1 的 someMethod");
}
}
--------------------
public class StrategySon2 implements Strategy {
@Override
public void method() {
System.out.println("StraterySon2 的 someMethod");
}
}
※
※
public class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void other() {
strategy.method();
}
}
※
※測試
Context ctn = new Context(new StrategySon1()); ctn.other(); new Context(new StrategySon2()).other();
※結果:
StraterySon1 的 someMethod
StraterySon2 的 someMethod
※使用匿名和 lambda
Xxx x1 = new Xxx(new Strategy(){
@Override
public void method(){
System.out.println("strategy1");
}
});
x1.m();
Xxx x2 = new Xxx(() -> System.out.println("strategy2"));
x2.m();
※還可以用匿名和 lambda,這樣 Impl 的 class 都不用寫了,也可以將他寫成共用方法
沒有留言:
張貼留言