策略模式

在策略模式(Strategy Pattern)中,一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。

在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的 context 对象。策略对象改变 context 对象的执行算法。

意图:定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。

主要解决:在有多种算法相似的情况下,使用 if...else 所带来的复杂和难以维护。

何时使用:一个系统有许多许多类,而区分它们的只是他们直接的行为。

如何解决:将这些算法封装成一个一个的类,任意地替换。

关键代码:实现同一个接口。

 

demo中的UML图如下:

具体代码实现,策略基类:

/**
 * @author Shuyu.Wang
 * @package:com.shuyu.strategy
 * @className:
 * @description:策略模式通用接口
 * @date 2018-11-08 16:31
 **/
public interface Strategy {

    double operation(double a,double b );
}

相关实现类:

/**
 * @author Shuyu.Wang
 * @package:com.shuyu.strategy
 * @description:加法实现类
 * @date 2018-11-08 16:44
 **/

public class OperationAdd implements Strategy{
    @Override
    public double operation(double a, double b) {
        return a+b;
    }
}




/**
 * @author Shuyu.Wang
 * @package:com.shuyu.strategy
 * @description:乘法计算类
 * @date 2018-11-08 16:47
 **/

public class OperationMul implements Strategy{
    @Override
    public double operation(double a, double b) {
        return a-b;
    }
}








/**
 * @author Shuyu.Wang
 * @package:com.shuyu.strategy
 * @description:减法类
 * @date 2018-11-08 16:46
 **/

public class OperationSub implements Strategy{
    @Override
    public double operation(double a, double b) {
        return a-b;
    }
}

结合上下文的Context:

/**
 * @author Shuyu.Wang
 * @package:com.shuyu.strategy
 * @description:
 * @date 2018-11-08 17:10
 **/


public class Context {
    Strategy strategy = null;

    public Context(Strategy strategy ) {
        this.strategy=strategy;
    }

    public double operation(double a,double b){
        return strategy.operation(a, b);
    }

}

测试类:


@RunWith(SpringRunner.class)
@SpringBootTest
public class StrategyApplicationTests {

		@Test
	public void contextLoads() {
		Context context=new Context(new OperationAdd());
		System.out.println(context.operation(10,5));
		context=new Context(new OperationSub());
		System.out.println(context.operation(10,5));
	}


}

运行结果如下:

15.0
 5.0

 

git代码地址:https://github.com/iot-wangshuyu/designpatterns/tree/master/strategy

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值