您的位置:首页 > 其它

设计模式学习笔记(四):策略模式【Strategy】

2014-06-18 09:17 686 查看
    刘备要到江东娶老婆了,走之前诸葛亮给赵云三个锦囊妙计,说是按天机拆开解决棘手问题。

    三个妙计是同一类型的东西,写个接口如下:

package com.example;

/**
* 首先定义一个策略接口,负责三个锦郎妙计的接口
*/
public interface IStrategy {

//每个锦郎妙计都是一个可执行的算法
public void operate();
}

     然后实现三个实现类,因为有三个妙计:

package com.example;

/**
* 找乔国老帮忙,是孙权不能杀刘备
*/
public class BackDoor implements IStrategy{

public void operate() {
System.out.println("找乔国老帮忙,让吴国太给孙权施加压力");
}
}
package com.example;

/**
* 求吴国太给开个绿灯
*/
public class GivenGreenLight implements IStrategy{

public void operate() {
System.out.println("求吴国太开个绿灯,放行!");
}
}
package com.example;

/*
* 孙夫人断后,挡住追兵
*/
public class BlockEnemy implements IStrategy{

public void operate() {
System.out.println("孙夫人断后,挡住追兵!");
}
}

    好了,三个妙计是有了,得有个锦囊要放这些妙计啊,锦囊定义如下:

package com.example;

/*
* 计谋有了,那还要有个锦郎
*/
public class Context {
//构造函数,你要使用哪一个妙计
private IStrategy strategy;
public Context(IStrategy strategy){
this.strategy = strategy;
}
//计谋有了,看我出招了
public void operater(){
this.strategy .operate();
}
}

     最后是赵云用了这三个锦囊化险为夷:

package com.example;

public class ZhaoYun {
/*
* 赵云出场,他根据诸葛亮的交代一次拆开妙计
*/
public static void main(String[] args){
Context context;
//刚刚到吴国时候拆开第一个
context = new Context(new BackDoor());
context.operater();

//刘备乐不思蜀,拆开了第二个
context = new Context(new GivenGreenLight());
context.operater();

//孙权的小兵追了,咋办?拆开第三个
context = new Context(new BlockEnemy());
context.operater();
}
}


      使用策略模式之后,代码的可读性和扩展性有了很大的提高,以后即使还需要添加新的算法,你也是手到擒来了。

       策略:它定义了算法家庭,分别封装起来。让他们之间可以互相替换,此模式让算法的变化不会影响到使用算法的用户。

package com.example;

public class ZhaoYun {
/*
* 赵云出场,他根据诸葛亮的交代一次拆开妙计
*/
public static void main(String[] args){
Context context;
//刚刚到吴国时候拆开第一个
context = new Context(new BackDoor());
context.operater();

//刘备乐不思蜀,拆开了第二个
context = new Context(new GivenGreenLight());
context.operater();

//孙权的小兵追了,咋办?拆开第三个
context = new Context(new BlockEnemy());
context.operater();
}
}


 

 

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: