设计模式---策略模式

今天又学习了一种模式,策略模式。总体感觉策略模式与简单工厂模式很像,简单工厂模式通过一个工厂类来创建具体产品角色,策略模式则通过上下文类来创建具体算法类。下面是一个以超市正常收费,打折,返利为场景的实例,将策略模式与简单工厂模式结合起来的一个例子。

(1)首先创建一个现金收费抽象类

/**
 * 现金收费抽象类
 * */
public abstract class CashSuper {

	abstract double acceptCash(double money);

}

(2)然后创建相应的算法实现类,如正常收费,打折,返利

/**
 * 正常收费子类
 * */
public class CashNormal extends CashSuper{

	@Override
	double acceptCash(double money) {
		return money;
	}

}
/**
 * 打折收费子类
 * */
public class CashRebate extends CashSuper{
	
	private double moneyDiscount;
	
	public CashRebate(double moneyDiscount) {
		this.moneyDiscount=moneyDiscount;
	}

	@Override
	double acceptCash(double money) {
		return moneyDiscount*money;
	}

}
/**
 * 返利收费子类
 * */
public class CashReturrn extends CashSuper{
	
	private double moneyCondition;
	
	private double moneyReturn;

	public double getMoneyCondition() {
		return moneyCondition;
	}

	public void setMoneyCondition(double moneyCondition) {
		this.moneyCondition = moneyCondition;
	}

	public double getMoneyReturn() {
		return moneyReturn;
	}

	public void setMoneyReturn(double moneyReturn) {
		this.moneyReturn = moneyReturn;
	}
	
	public CashReturrn(double moneyCondition,double moneyReturn) {
		this.moneyCondition=moneyCondition;
		this.moneyReturn=moneyReturn;
	}

	@Override
	double acceptCash(double money) {
		return money-Math.floor(money/moneyCondition)*moneyReturn;
	}
	
}
(3)创建策略类

/**
 * 策略类
 * */
public class StrategyContext {
	
	private CashSuper cashSuper;
	
	public StrategyContext(int type){
		switch (type) {
			case Constants.NORMAL_TYPE:
				cashSuper=new CashNormal();
				break;
			case Constants.DISCOUNT_TYPE:
				cashSuper=new CashRebate(0.8);
				break;
			case Constants.RETURN_TYPE:
				cashSuper=new CashReturrn(500,100);
				break;
		}
	}
	
	public double getResult(double money) {
		
		return cashSuper.acceptCash(money);
	}

}
(4)测试类

public class Test {
	
	public static void main(String[] args) {
		
		StrategyContext context=new StrategyContext(Constants.RETURN_TYPE);
		double actualMoney=context.getResult(600);
		System.out.println(actualMoney);
	}

}

输出:

500.0




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值