策略模式
该模式定义了一系列算法,并将每个算法封装起来,使它们可以相互替换,且算法的变化不会影响使用算法的客户。
以做鱼为例,可以做红烧鱼,水煮鱼,通过环境指定某一种鱼,具体做法由抽象类的实现类来做,且可以随意替换。
public class CategoryTest {
public static void main(String[] args) {
Fish hotFish = new HotFish();
Fish redCookedFish = new RedCookedFish();
// 做水煮鱼
CookContext cookContext = new CookContext();
cookContext.setFish(hotFish);
cookContext.cooke();
System.out.println("----------------------------");
// 做红烧鱼
cookContext.setFish(redCookedFish);
cookContext.cooke();
}
}
interface Fish{
void cook();
}
class HotFish implements Fish{
@Override
public void cook() {
System.out.println("做水煮鱼");
}
}
class RedCookedFish implements Fish{
@Override
public void cook() {
System.out.println("做红烧鱼鱼");
}
}
class CookContext {
private Fish fish;
public Fish getFish() {
return fish;
}
public void setFish(Fish fish) {
this.fish = fish;
}
void cooke(){
this.fish.cook();
}
}
参考资料:
1.http://c.biancheng.net/view/1378.html
代码地址:https://gitee.com/zhoujie1/design-mode-and-principle.git