zoukankan      html  css  js  c++  java
  • 第二章 策略模式

    策略模式封装了变化。

    标准策略模式:

    /**
     * Created by hero on 16-3-29.
     */
    public abstract class CashSuper {
        public abstract double acceptCash(double money);
    }
    /**
     * Created by hero on 16-3-29.
     */
    public class CashNormal extends CashSuper{
        @Override
        public double acceptCash(double money) {
            return money;
        }
    }
    /**
     * Created by hero on 16-3-29.
     */
    public class CashRebate extends CashSuper {
        private double moneyRebate = 1d;
    
        public double getMoneyRebate() {
            return moneyRebate;
        }
    
        public void setMoneyRebate(double moneyRebate) {
            if (moneyRebate < 0) {
                throw new IllegalArgumentException("what's wrong with this supermarket?!!!");
            }
            this.moneyRebate = moneyRebate;
        }
    
        public CashRebate(double moneyRebate) {
            this.setMoneyRebate(moneyRebate);
        }
    
        @Override
        public double acceptCash(double money) {
            return getMoneyRebate() * money;
        }
    }
    /**
     * Created by hero on 16-3-29.
     */
    public class CashContext {
        private CashSuper cashSuper = null;
    
        public CashContext(CashSuper cashSuper) {
            this.cashSuper = cashSuper;
        }
    
        public double getResult(double money) {
            return cashSuper.acceptCash(money);
        }
    }
    public class Main {
    
        public static void main(String[] args) {
            CashContext cashContext = null;
            cashContext = new CashContext(new CashNormal());
            System.out.println(cashContext.getResult(12));
            cashContext = new CashContext(new CashRebate(0.3));
            System.out.println(cashContext.getResult(12));
        }
    }

    策略与简单工厂结合:

    简单工厂模式对类似“满300减200、满400减100”的变化进行有效封装,除非另外制定一套规则比如:“满减-400,100、满减-500,100”,在swich语句中只取‘-’之前的作case条件,其后跟参数,多个参数以

    ‘,’分割。

    策略与简单工厂的结合使后端对前端的暴露降低了。算是集成了二者的优点吧。

  • 相关阅读:
    Socket与系统调用深度分析
    需求分析:未来的图书会是怎么样的?
    构建调试Linux内核网络代码的环境MenuOS系统
    jmeter--开始
    pytest---api
    pytest---mark
    pytest---数据处理
    pytest---fixture运行规则
    pytest---allure(mac版本)
    pytest---pytest.ini
  • 原文地址:https://www.cnblogs.com/littlehoom/p/5335471.html
Copyright © 2011-2022 走看看