策略模式

策略模式(Strategy),定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。本模式使得算法的变化可独立于使用它的客户。

package gof23;

public class StrategyTest {
	public static void main(String[] args) {
		CashContext cc = null;
		cc = new CashContext("正常收费");
		System.out.println("收费为:" + cc.getResult(2000) +"元");
		cc = new CashContext("满300返100");
		System.out.println("收费为:" + cc.getResult(2000) +"元");
		cc = new CashContext("打8折");
		System.out.println("收费为:" + cc.getResult(2000) +"元");
	}
}

class CashContext {
	private CashSuper cs = null;
	public CashContext(String type) {
		switch(type) {
		case "正常收费":
			CashNormal cs0 = new CashNormal();
			cs = cs0;
			break;
		case "满300返100":
			CashReturn cs1 = new CashReturn(300, 100);
			cs= cs1;
			break;
		case "打8折":
			CashRebate cs2 = new CashRebate(0.8);
			cs = cs2;
			break;
		}
	}
	
	public double getResult(double money) {
		return cs.acceptCash(money);
	}
}

abstract class CashSuper {
	public abstract double acceptCash(double money);
}

/*
 * 正常收费,原价返回
 */
class CashNormal extends CashSuper {

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

/*
 * 打折收费,初始化时,需要输入折扣率,如0.8
 */
class CashRebate extends CashSuper {
	private double moneyRebate = 1d;
	public CashRebate(double moneyRebate) {
		this.moneyRebate = moneyRebate;
	}
	@Override
	public double acceptCash(double money) {
		return money * moneyRebate;
	}
	
}

/*
 * 返利收费,初始化时必须输入返利条件和返利值,比如满300返100,
 * 则moneyCondition为300,moneyReturn为100
 */
class CashReturn extends CashSuper {
	private double moneyCondition = 0.0d;
	private double moneyReturn = 0.0d;
	public CashReturn(double moneyCondition, double moneyReturn) {
		this.moneyCondition = moneyCondition;
		this.moneyReturn = moneyReturn;
	}
	@Override
	public double acceptCash(double money) {
		double result  = money;
		if(result > moneyCondition)
			result = money - Math.floor(money / moneyCondition) * moneyReturn;
		return result;
	}
	
}

运行结果为:

收费为:2000.0元
收费为:1400.0元
收费为:1600.0元


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值