zoukankan      html  css  js  c++  java
  • 多线程04.策略模式

    策略模式的使用:

    一个计算税率的例子:

    package chapter2;
    
    /**
     * 计算方法的接口
     */
    public interface CalculatorStrategy {
        public double calclate(double salary,double bonus);
    }
    package chapter2;
    
    public class SimpleCalculatorStrategy implements  CalculatorStrategy {
        private  final  static  double SAQLARY_RATE=0.1;
        private  final  static  double BONUS_RATE=0.15;
    
    
        @Override
        public double calclate(double salary, double bonus) {
            return salary*SAQLARY_RATE+bonus*BONUS_RATE;
        }
    }
    package chapter2;
    /*
    策略模式
     */
    public class TaxCalaculator {
        private final  double salary;
        private final  double bonus;
    //注入策略,使用了那种计算方案
     private   CalculatorStrategy CalculatorStrategy;
     public TaxCalaculator(double salary,double bonus){
         this.salary=salary;
         this.bonus=bonus;
     }
    
        public double getSalary() {
            return salary;
        }
    
        public double getBonus() {
            return bonus;
        }
    
        /**
         * 子类重写
         * @return
         */
        protected double calcTax() {
            return CalculatorStrategy.calclate(salary,bonus);
        }
    
        public double calcuate() {
            return this.calcTax();
        }
    
        public void setCalculatorStrategy(CalculatorStrategy calculatorStrategy) {
            CalculatorStrategy = calculatorStrategy;
        }
    }

    调用:

    package chapter2;
    
    public class Bank3 {
        public static void main(String[] args) {
            /**
             * 计算要交多少钱的税, 使用了策略模式
             */
         /*   TaxCalaculator tor = new TaxCalaculator(1000d, 2000d){
                @Override
                protected double calcTax() {
                   return getBonus()*0.15+getSalary()*0.1;
                }
            };
    
            double tax = tor.calcuate();
            System.out.println(tax);*/
            TaxCalaculator tor = new TaxCalaculator(1000d, 2000d);
            SimpleCalculatorStrategy scs = new SimpleCalculatorStrategy();
            tor.setCalculatorStrategy(scs);
            System.out.println(tor.calcuate());
        }
    }
  • 相关阅读:
    help python(查看模块帮助文档)
    Vim常用快捷键
    tar 解压缩
    目前的学习计划
    学习方向
    C#转Python计划
    困惑的屌丝,求方向。。。
    修改PYTHONPATH的一种方法(在Window平台和Ubuntu下都有效)
    使用正则表达式统计vs项目代码总行数[转]
    日常工作细节汇总
  • 原文地址:https://www.cnblogs.com/q1359720840/p/10649386.html
Copyright © 2011-2022 走看看