关于策略模式的一些问题

本文探讨了策略模式与工厂模式的区别,以及如何通过策略模式减少if-else判断。文章列举了两种策略模式的实现方式,并指出真正消除if-else的是HashMap的使用。同时强调了Context类在策略模式中的必要性,以实现更好的解耦合和代码维护。
摘要由CSDN通过智能技术生成

不渴望能够一跃千里,只希望每天能够前进一步。

光阴易逝,岂容我待。

最近学习了下设计模式,发现了一些问题,记录下来。

目录

1、工厂模式和策略模式有什么区别?

2、策略模式真的能省略if和else判断吗?

3、策略模式是否有必要写个上下文类()Context?


在总结上面三个问题回答之前,我们先来写一遍策略模式。

网上的策略模式有多种写法,这里只举栗2种:

首先是没用设计模式之前的代码:

public Result calcPrice(int customerType){
    //判断客户类型执行不同计算价格方法
    if(customerType == 1){
        //计算白银客户优惠价..
    }else if(customerType == 2){
        //计算黄金客户优惠价..
    }else if(customerType == 3){
        //计算钻石客户优惠价..
    }
    .....
    else{
        //计算xx客户优惠价..
    }
}

策略模式第一种写法:

在客户端根据传入的策略类来判断

//价格策略接口
public interface IPriceStrategy{
    Result calcPrice();
}

//白银客户价格策略类
public class SilverPriceStrategy implements IPriceStrategy{
    Result calcPrice(){
        //计算白银客户优惠价..
    }
}

//黄金客户价格策略类
public class GoldPriceStrategy implements IPriceStrategy{
    Result calcPrice(){
        //计算黄金客户优惠价..
    }
}

//钻石客户价格策略类
public class DiamondPriceStrategy implements IPriceStrategy{
    Result calcPrice(){
        //计算钻石客户优惠价..
    }
}
...

//价格策略上下文类
public class CustomerPriceContext{
    private IPriceStrategy iPriceStrategy;
    
    public CustomerPriceContext(IPriceStrategy iPriceStrategy){
        this.iPriceStrategy = iPriceStrategy;
    }

    public Result calcPrice(){
        return this.iPriceStrategy.calcPrice();
    }
}

===============================================
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值