声明:文章内容根据大牛博客的内容,自己理解后,给自己做的学习笔记,文末会附上大牛博客地址链接。有需要沟通交流的可加我QQ群:425120333
策略模式是一种很常用,也很实用的一种设计模式。要使用策略模式就要求编写面向抽象(接口或者抽象类)的代码。
举个简单的例子来理解下策略模式。有一句古话说的是“条条大路通罗马”,这说明达到目的地的方法不是唯一,每个人都有自己的方法。
这里面的每个方法就相当于一个策略,具体使用何种策略,根据实际的人不同而会有所不一样。
首先要有个去罗马的接口,里面包含了一个去罗马的方法。
interface ArriveRome {
void achieveMethod();
}
然后是他的实现方法,这里我写了三个:
class ArriveWithCar implements ArriveRome {
@Override
public void achieveMethod() {
System.out.println("通过坐车到达罗马。。。");
}
}
class ArriveWithShip implements ArriveRome {
@Override
public void achieveMethod() {
System.out.println("通过坐船到达罗马。。。");
}
}
class ArriveWithPlane implements ArriveRome {
@Override
public void achieveMethod() {
System.out.println("通过坐飞机到达罗马。。。");
}
}
然后就是具体的人了:
class Person {
private String name;
private ArriveRome arriveRome;
public Person(String name) {
this.name = name;
}
public void setArriveRome(ArriveRome arriveRome) {
this.arriveRome = arriveRome;
}
public void gotoRome() {
System.out.print("我是" + name);
arriveRome.achieveMethod();
}
}
最后通过客户端类来调用下看下整体效果:
public class RomeClient {
public static void main(String[] args) {
Person person1 = new Person("张三");
ArriveRome arriveRome1 = new ArriveWithShip();
person1.setArriveRome(arriveRome1);
person1.gotoRome();
Person person2 = new Person("李四");
ArriveRome arriveRome2 = new ArriveWithShip();
person2.setArriveRome(arriveRome2);
person2.gotoRome();
Person person3 = new Person("王五");
ArriveRome arriveRome3 = new ArriveWithShip();
person3.setArriveRome(arriveRome3);
person3.gotoRome();
}
}
控制台输出:
我是张三通过坐船到达罗马。。。
我是李四通过坐船到达罗马。。。
我是王五通过坐船到达罗马。。。
通过使用策略模式,使得代码的扩展变得更加容易,上述代码中如果要新提添加一种到达罗马的方法,只要实现ArriveRome接口就行,
该模式的关键是具体类(这里是person)对策略的使用是通过声明接口(private ArriveRome arriveRome),
具体的实现是在高层模块(RomeClient)指定。这使得所有代码更加容易维护,和扩展。
参考大牛链接:http://www.cnblogs.com/zuoxiaolong/p/pattern8.html