设计模式之策略模式

策略模式:
spring框架访问资源属性就采用了策略模式,那么什么是策略模式呢,策略模式为我们解决什么问题呢:
实现某一功能有多种算法或者策略,我们可以根据不同的条件选择不同的算法或者策略,但是如何切换算法而不使得算法和对象耦合,这就要使用策略模式:他定义一系列的算法,将每个算法单独封装起来,并使算法间可以相互替换。由此可以看出策略模式使得算法可独立于使用它的客户而变化。

下面我们参照一个打折算法的实例来了解策略模式:

//策略模式的接口设计:实现这个接口就可以实现打折,但具体的打折策略与该接口无关,而是有具体的实现类来决定打折策略。
public interface DiscountStrategy{
//定义一个用于计算打折的方法。
double getDiscount(double originPrice);
}

//VIP打折策略
public class VIPDiscount implements DiscountStrategy{
//重写getDiscount()方法
public double getDiscount(double originPrice){
return originPrice*0.5;
}
}

//折旧打折
public class OldDiscount implements DiscountStrategy{
public double getDiscount(double originPrice){
return originPrice*0.7;
}
}

//以上是两种打折的策略,但是如果客户端代码直接与具体的策略进行耦合,那么客户端将无法实现解耦,因此策略模式提供了一个类,让它为客户端代码决定采用哪种策略:
public class DiscountContext{
//组合一个DiscountStrategy对象
private DiscountStrategy strategy;

public DiscountContext(DiscountStrategy strategy){
this.strategy = strategy;
}


//根据实际使用的DiscountStrategy对象进行打折
public double getDiscountPrice(double price){
//如果strategy为null,系统采用折旧策略打折
if(strategy == null){
strategy = new OldDiscount();
}
return this.strategy.getDiscount(price);
}

//提供切换算法的方法
public void changeDiscount(DiscountStrategy strategy){
this.strategy = strategy
}
}


DiscountContext这个类在此充当决策者的角色。他决定采用哪种策略进行打折.

//测试类
public class StrategyTest{
public static void main(String[] args){
// 客户端没有选择打折策略类
DiscountContext dc = new DiscountContext(null);
double price1 = 79;

// 使用默认的打折策略
System.out.println("79 元的书默认打折后的价格是:" + dc.getDiscountPrice(price1));

// 客户端选择合适的 VIP 打折策略
dc.changeDiscount(new VipDiscount());
double price2 = 89;

// 使用 VIP 打折得到打折价格
System.out.println("89 元的书对 VIP 用户的价格是:" + dc.getDiscountPrice(price2));
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值