策略模式Strategy (分离算法,选择实现)

一:使用场景

假如领导要让我们做个报价方案。

那我们可定会有这样的情况,

1.新用户或者普通用户,报市场价

2.老用户给9.5折

3.优质客户或大客户给9折

二:不用设计模式,普通我们的 开发代码

/**
 * 报价管理不同等级的用户,价格不一样
 * @author dy
 * @since 2016-08-10  & JDK 1.8.0_91
 */
public class Price_ {
    /**
     * 这里不用设计模式的解决方案
     */
    public double quote(double goodPrice,String customerType){
        switch (customerType){
            case "普通客户":
                return goodPrice;
            case "老客户":
                return goodPrice*0.95;
            case "大客户":
                return goodPrice*0.90;
            default:
                return goodPrice;
        }
    }
}

作为一个老鸟程序员,不用多说这样写可定code review 过不去,可能会被吐槽...

三,解决方案,这里我们引入策略模式,

下面是策略模式的结构和说明:

四:我们用策略模式实现报价管理

/**
 * 报价管理不同等级的用户,价格不一样
 *
 * @author dy
 * @since 2016-08-10  & JDK 1.8.0_91
 */
public class Price {
    
    // 上下文对象,通常持有一个具体策略对象
    private Strategy strategy;

    public Price(Strategy strategy) {
        this.strategy = strategy;
    }
    /**
     * 用设计模式的解决方案
     */
    public double quote(double goodPrice){
        return this.strategy.calcPrice(goodPrice);
    }
}
/**
 * 策略接口
 * @author dy
 * @since 2016-08-10  & JDK 1.8.0_91
 */
public interface Strategy {
    /**
     * 某算法接口
     */
    void algorithmInteface();

    /**
     * 计算价格
     * @param goodPrice
     * @return
     */
    double calcPrice(double goodPrice);
}
public class NormalCustomerStrategy implements Strategy {
    @Override
    public void algorithmInteface() {

    }

    @Override
    public double calcPrice(double goodPrice) {
        return goodPrice;
    }
}
public class OldCustomerStrategy implements Strategy {
    @Override
    public void algorithmInteface() {

    }

    @Override
    public double calcPrice(double goodPrice) {
        return goodPrice*0.95;
    }
}
public class BigCustomerStrategy implements Strategy {
    @Override
    public void algorithmInteface() {

    }

    @Override
    public double calcPrice(double goodPrice) {
        return goodPrice*0.90;
    }
}
/**
 * @author dy
 * @since 2016-08-10  & JDK 1.8.0_91
 */
public class Client {
    public static void main(String[] args) {

        double goodsPrice = 1000;//商品市场价

        Strategy strategy = new BigCustomerStrategy();//商品策略

        Price ctx = new Price(strategy);//上下文

        System.out.println(ctx.quote(1000));//对应报价
    }
}

五:

策略模式的重心不是如何实现算法,而是如何组织、调用这些算法,从而使得程序结构更加灵活,具有更好的维护性和扩展性。

转载于:https://my.oschina.net/dyyweb/blog/730660

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值