当前位置: 移动技术网 > IT编程>开发语言>Java > 设计模式之 Strategy(策略)通俗理解

设计模式之 Strategy(策略)通俗理解

2020年07月27日  | 移动技术网IT编程  | 我要评论

1 Strategy定义

Strategy 策略模式是属于设计模式中 对象行为型模式,主要是定义一系列的算法,把这些算法一个个封装成单独的类。

策略模式简单来说就是将一个对象的多个具体策略进行独立封装起来,彼此之间可进行替换。

2 如何使用?

举例:超市买了本书“架构设计师”66元,不同会员的折扣是不同的;不同的结算方式就相当于一个一个策略;

package xx.study.design.strategy;


import java.math.BigDecimal;

/**
 * 收银员
 */
public class StrategyDemo {
    private Customer customer;

    private BigDecimal cost(BigDecimal oldCost) {
        return customer.cost(oldCost);
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public static void main(String[] args) {
        StrategyDemo cashier = new StrategyDemo();
        CommonCustomer commonCustomer = new CommonCustomer();
        SuperVipCustomer superCustomer = new SuperVipCustomer();
        VipCustomer vipCustomer = new VipCustomer();
        //买了本书“架构设计师” 花了66元
        BigDecimal bigDecimal = new BigDecimal(66);
        //调用不同算法
        cashier.setCustomer(commonCustomer);
        System.out.printf("普通用户需要支付:%f\n",cashier.cost(bigDecimal).doubleValue());
        cashier.setCustomer(vipCustomer);
        System.out.printf("vip用户需要支付:%f\n",cashier.cost(bigDecimal).doubleValue());
        cashier.setCustomer(superCustomer);
        System.out.printf("超级vip用户需要支付:%f\n",cashier.cost(bigDecimal).doubleValue());
    }
}

 

package xx.study.design.strategy;


import java.math.BigDecimal;

/**
 * 策略接口
 */
public interface Customer {
    /**
     * 计算折扣后的花费
     * @param oldCost 原花费
     * @return 折扣后的花费
     */
    public BigDecimal cost(BigDecimal oldCost);
}
package xx.study.design.strategy;


import java.math.BigDecimal;

/**
 * 可以看成一个一个策略封装
 */
public class CommonCustomer implements Customer {
    @Override
    public BigDecimal cost(BigDecimal oldCost) {
        return oldCost.multiply(new BigDecimal(0.8));
    }
}

 

package xx.study.design.strategy;

import java.math.BigDecimal;

public class VipCustomer implements Customer {
    @Override
    public BigDecimal cost(BigDecimal oldCost) {
        return oldCost.multiply(new BigDecimal(0.7));
    }
}
package xx.study.design.strategy;

import java.math.BigDecimal;

public class SuperVipCustomer implements Customer {

        @Override
        public BigDecimal cost(BigDecimal oldCost) {
            return oldCost.multiply(new BigDecimal(0.6));
        }

}

 

 

本文地址:https://blog.csdn.net/h4241778/article/details/107589465

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网