策略访问模式

来源:互联网 发布:算法导论实现 编辑:程序博客网 时间:2024/06/01 15:51

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

/** * 策略访问模式 接口定义       * @author zhangjianbin * */public interface Strategy {    double getPrice(double standprice);}
/** * 新客户小量购买策略 * * @author zhangjianbin * */public class NewCoustomerfewStrategy implements Strategy{    @Override    public double getPrice(double standprice) {        System.err.println("新客户小量购买算法:不打折");        return standprice;    }}
/** * 新客户大量购买策略 * * @author zhangjianbin * */public class NewCoustomerManyStrategy implements Strategy{    @Override    public double getPrice(double standprice) {        System.err.println(" 新客户大量购买算法:打9.5折");        return standprice*0.95;    }}
/** * 老客户小量购买策略 * * @author zhangjianbin * */public class OldCoustomerfewStrategy implements Strategy{    @Override    public double getPrice(double standprice) {        System.err.println("老客户小量购买算法:打9折");        return standprice*0.9;    }}
/** * 老客户大量购买策略 * * @author zhangjianbin * */public class OldCoustomerManyStrategy implements Strategy{    @Override    public double getPrice(double standprice) {        System.err.println("老客户老客户大量购买算法:打8.5折");        return standprice*0.9;    }}
/** * 管理策略算法 *  负责与俱类的策略类交互 *   *  优点: *      俱体的算法和直接与客户端之间的调用分离了 *      使算法可以独立于客户端变化 * @author zhangjianbin * */public class Context {    private Strategy strategy;    public Context(Strategy strategy) {        super();        this.strategy = strategy;    }    public void pringPrice(double standprice){        System.err.println("策略算法报价:"+strategy.getPrice(standprice));    }}
public class Client {    public static void main(String[] args) {        /**         * 采用老客户大量购买策略算法         */        Strategy strategy = new OldCoustomerManyStrategy();        /**         * 管理算法对象           *      根据注入的算法,自动进行打折计算         */        Context context = new Context(strategy);        /**         * 打折算法计算后的价格         *          传入原价         */        context.pringPrice(8220);        /**         * 结果:         * 老客户老客户大量购买算法:打8.5折         *  策略算法报价:7398.0         */    }}
0 0
原创粉丝点击