1.分析项目中变化部分与不变部分
2.多用组合,少用继承;用行为类组合,而不是行为的继承
案例:
第一步,把行为抽象为接口
package top.littlepage.designPattern.Strategy; public interface FlyBehavior { void fly(); }
第二步,把具体行为用实体类实现
package top.littlepage.designPattern.Strategy; public class BadFly implements FlyBehavior{ @Override public void fly() { System.out.println("--bad fly--"); } }
package top.littlepage.designPattern.Strategy; public class NotFly implements FlyBehavior{ @Override public void fly() { System.out.println("--not fly--"); } }
package top.littlepage.designPattern.Strategy; public class GoodFly implements FlyBehavior{ @Override public void fly() { System.out.println("--good fly--"); } }
第三步,做出具体的环境进行实现该实体
package top.littlepage.designPattern.Strategy; public class Bird { private String name; private int age; private GoodFly goodfly; private BadFly badfly; private NotFly notfly; public Bird() { name=""; age=0; goodfly=new GoodFly(); badfly=new BadFly(); notfly=new NotFly(); } public GoodFly getGoodfly() { return goodfly; } public void setGoodfly(GoodFly goodfly) { this.goodfly = goodfly; } public BadFly getBadfly() { return badfly; } public void setBadfly(BadFly badfly) { this.badfly = badfly; } public NotFly getNotfly() { return notfly; } public void setNotfly(NotFly notfly) { this.notfly = notfly; } public Bird(String name, int age) { this.name = name; this.age = age; goodfly=new GoodFly(); badfly=new BadFly(); notfly=new NotFly(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
测试:
package top.littlepage.designPattern.Strategy; public class Test { public static void main(String[] args) { Bird b=new Bird("小鸟",2); System.out.print(b.getName()); b.getGoodfly().fly(); System.out.print(b.getName()); b.getBadfly().fly(); System.out.print(b.getName()); b.getNotfly().fly(); } }
控制台截图
策略模式(strategy)利用接口进行抽象,利用实体进行实现抽象,再做出环境进行实现具体的实体
在我们面向对象后,经常利用这种设计模式进行编程,应该是比较简单的一种模式