您的位置:首页 > 编程语言 > Java开发

JAVA设计模式之策略模式

2017-11-05 20:47 309 查看

1、定义


策略模式:定义一组算法,将每个算法都封装起来,使得它们之间可以相互替换。策略模式让算法独立于调用它的客户端而独立变化。
策略模式使这组算法能互不影响地变化,当客户端调用它们的时候。

2、策略模式中有三个角色


(1)抽象策略(Strategy):通常由接口或抽象类实现。定义了多个具体策略的公共接口,具体策略类中各种不同的算法以不同的方式实现这个接口;Context使用这些接口调用不同实现的算法。

(2)具体策略(ConcreteStrategy):实现Strategy接口或继承于抽象类Strategy,封装了具体的算法和行为。

(3)环境类(Contex):持有一个公共策略接口的引用,直接给客户端调用。


3、策略模式的结构图





4、策略模式实现思路


(1)给策略对象定义一个公共接口(Strategy)

1 public interface Strategy {
2     public void algorithm();
3 }


(2)定义具体的策略类(ConcreteStrategy),实现上面的接口

public class FirstStrategy implements Strategy {

@Override
public void algorithm() {
System.out.println("First Algorithm.");
}

}


public class SecondStrategy implements Strategy {

@Override
public void algorithm() {
System.out.println("Second Algorithm.");
}

}


(3)定义一个环境类(Contex),类中持有一个对公共接口的引用,以及相应的get、set方法、构造方法

public class Context {
Strategy strategy;

public Context(Strategy strategy) { //构造函数
super();
this.strategy = strategy;
}

public Strategy getStrategy() { //get方法
return strategy;
}

public void setStrategy(Strategy strategy) { //set方法
this.strategy = strategy;
}

public void algorithm() {
strategy.algorithm();
}
}


最后,客户端自由调用策略^_^

public class StrategyClient {

public static void main(String[] args) {
//使用构造函数选择策略
Context context=new Context(new FirstStrategy());
context.algorithm();

//使用get、set方法切换策略
//Context context=new Context();
//contex.set(new FirstStrategy());
//context.algorithm();

//切换到另一个策略
Context secondContext=new Context(new SecondStrategy());
secondContext.algorithm();

//Context secondContext=new Context();
//secondContext.set(new SecondStrategy());
//secondContext.algorithm();
}

}



5、小结


(1)策略模式的重点在于,给对象传入什么样的策略,就执行什么样的动作。
(2)策略模式优点:可以轻易的扩展与改变策略,可以动态改变对象的行为。
(3)策略模式缺点:客户端必须知道所有的策略类,并自行决定使用哪一种。每个具体的策略都会产生一个新类,这样会造成很多策略类。

6、自己写了个完整策略模式demo,解压即可运行,需要的留下邮箱。

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