zoukankan      html  css  js  c++  java
  • 大话设计模式笔记 策略模式

    package strategy;
    
    public abstract class CashSuper {
        // 现金收费抽象类
        public abstract double acceptCash(double money);
    }
    package strategy;
    
    public class CashRebate extends CashSuper {
    
        private double moneyRebate = 1;
    
        // 打折收费类 默认1 既是不打折
        public CashRebate(double moneyRebate) {
            this.moneyRebate = moneyRebate;
        }
    
        @Override
        public double acceptCash(double money) {
            return money * moneyRebate;
        }
    
    }
    package strategy;
    
    public class CashReturn extends CashSuper {
    
        // 返利条件 满
        private double moneyCondition = 0;
        // 返利多少
        private double moneyReturn = 0;
    
        public CashReturn(double moneyCondition, double moneyReturn) {
            this.moneyCondition = moneyCondition;
            this.moneyReturn = moneyReturn;
        }
    
        //我的理解是达到满300返利100,满600返利250,这种情况的
        @Override
        public double acceptCash(double money) {
            double result = money;
            if (money >= moneyCondition) {
                result = money - moneyReturn;
            }
            return result;
        }
    
    }
    package strategy;
    
    public class CashContext {
        private CashSuper cs;
    
        public CashContext(String type) {
            switch (type) {
            case "打折":
                CashRebate cs0=new CashRebate(0.8);
                cs=cs0;
                break;
            case "满300返100":
                CashReturn cr1=new CashReturn(300, 100);
                cs=cr1;
                break;
    
            }
        }
        
        public double GetResult(double money){
            return cs.acceptCash(money);
        }
    }
    package strategy;
    
    public class Test {
        public static void main(String[] args) {
            double total=0;
            CashContext csuper=new CashContext("打折");
            double money=100;
            total=csuper.GetResult(money);
            System.out.println(total);
        }
    }

    感觉策略模式和简单工厂差不多的样子,一个工厂类用静态方法类传参生成对象,一个用构成方法传参数生成对象。

    个人倾向于静态方法类传参生成对象,没必要的对象可以不用生成。

  • 相关阅读:
    JavaScript快速入门-DOM对象
    JavaScript快速入门-ECMAScript对象介绍
    JavaScript快速入门-ECMAScript函数
    JavaScript快速入门-ECMAScript运算符
    [转] boost::function用法详解
    [转] [翻译]图解boost::bind
    [转] Git 分支
    [转] 多线程下变量-gcc原子操作 __sync_fetch_and_add等
    [转] Boost智能指针——scoped_ptr
    [转] linux下的c/c++调试器gdb
  • 原文地址:https://www.cnblogs.com/linkarl/p/4776111.html
Copyright © 2011-2022 走看看