打折算法 Java_JAVA算法策略模式之商品打折 满x送x

场景:某超市收银台,营业员根据客户购买的商品和数量向客户收费.

问题:超市某段时间会有打折活动(例如打8折),满XXX元送XXX元活动,满XXX元送XXX积分活动等等.

算法类,可能是打折,满XX送XX等等

package com.hebo.test.designmode.strategy;

public abstract class Strategy {

//算法方法

public abstract void AlgorithmInterface();

}

打折算法实现

package com.hebo.test.designmode.strategy;

/**

* 模拟打折类

* @author HeBo

*

*/

public class ConcreteStrategyA extends Strategy {

@Override

public void AlgorithmInterface() {

System.out.println("打折算法实现..");

}

}模拟满xx送xx元活动

package com.hebo.test.designmode.strategy;

/**

* 模拟满xx送xx元活动

* @author HeBo

*

*/

public class ConcreteStrategyB extends Strategy {

@Override

public void AlgorithmInterface() {

System.out.println("满XX送XX元算法实现..");

}

}模拟满XX元送XX积分

package com.hebo.test.designmode.strategy;

/**

* 模拟满XX元送XX积分

* @author HeBo

*

*/

public class ConcreteStrategyC extends Strategy {

@Override

public void AlgorithmInterface() {

System.out.println("满XX元送XX积分算法实现..");

}

}上下文

package com.hebo.test.designmode.strategy;

public class Context {

Strategy strategy;

public Context(String type){

if(type.equals("打折")){

strategy = new ConcreteStrategyA();

return;

}

if(type.equals("满就送")){

strategy = new ConcreteStrategyB();

return;

}

if(type.equals("送积分")){

strategy = new ConcreteStrategyC();

return;

}

}

//不使用工厂模式的构造函数

public Context(Strategy strategy){

this.strategy = strategy;

}

//上下文接口

public void ContextInterface(){

strategy.AlgorithmInterface();

}

}测试类

package com.hebo.test.designmode.strategy;

/**

* 模拟收银台

* @author HeBo

*

*/

public class Test {

static Context context;

public static void main(String[] args) {

context = new Context("打折");

context.ContextInterface();

context = new Context("满就送");

context.ContextInterface();

context = new Context("送积分");

context.ContextInterface();

/*Context不使用工厂模式的测试代码

* context = new Context(new ConcreteStrategyA());

context.ContextInterface();

context = new Context(new ConcreteStrategyB());

context.ContextInterface();

context = new Context(new ConcreteStrategyC());

context.ContextInterface();*/

}

}

总结:策略模式是一种定义一系列算法的方法,从概念上看,所有这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少各种算法类与使用算法类之间的耦合。

策略模式的Strategy类为Context定义了一系列的可供重用的算法和行为。另外一个优点是简化了单元测试,每个算法都有自己的类,可以通过自己单独接口进行测试。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值