码迷,mamicode.com
首页 > 其他好文 > 详细

二、使用简单工厂来改进策略模式

时间:2017-09-22 00:40:42      阅读:281      评论:0      收藏:0      [点我收藏+]

标签:结构   实现   targe   参考   ext1   []   内容   字符串   cut   

策略模式的使用,把一系列算法进行了封装,只需要通过配置不同的算法,即可以实现算法的自由切换。具体内容参考第一篇:http://www.cnblogs.com/lay2017/p/7570041.html

但是,由于有不同的策略,那么我们就需要在使用的时候进行策略的选择,例如:

String strategyName = "strategy1";

Strategy strategy = null;

switch(strategyName){
    case "strategy1":
        strategy = new strategy1();
    break;
    case "strategy2":
        strategy = new strategy2();
    break;
    default:
    break;
}

StrategyContext strategyContext = new StrategyContext(strategy);
strategyContext.executeSay();

我们看到,使用这个策略模式封装的功能相当的麻烦。尤其是这个switch分支结构,那我们是不是考虑把这个分支结构放入到策略模式中呢?使用的时候,只需要传入一个字符串即可。

完整代码如下:

public class StrategyDemo {
    
    public static void main(String[] args) {
        StrategyContext strategyContext1 = new StrategyContext("strategy1");
        strategyContext1.executeSay();
    }
}

// 功能类
class StrategyContext{
    
    private Strategy strategy;
    
    public StrategyContext(String strategyName){
        switch (strategyName) {
        case "strategy1":
            this.strategy = new Strategy1();
            break;
        case "strategy2":
            this.strategy = new Strategy2();
            break;
        default:
            break;
        }
    }
    
    public void executeSay(){ // 执行策略
        strategy.say();
    }
}

// 策略接口
interface Strategy{
    public void say();
}

// 具体策略1实现
class Strategy1 implements Strategy{

    @Override
    public void say() {
        System.out.println("executing strategy1");
    }
}

// 具体策略2实现
class Strategy2 implements Strategy{

    @Override
    public void say() {
        System.out.println("executing strategy2");
    }
}

StrategyContext只是传入了一个字符串,我们把选择策略的分支结构从使用的地方分离到了策略的配置类当中。

事实上,switch这个分支结构被放入到配置类当中,通过传入字符串实例化不同策略的过程就是简单工厂的实现。所以在这里,我们用简单工厂来改进了策略模式,大大降低了使用和实现的耦合

二、使用简单工厂来改进策略模式

标签:结构   实现   targe   参考   ext1   []   内容   字符串   cut   

原文地址:http://www.cnblogs.com/lay2017/p/7572105.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!