状态模式

动机:对象的状态经常面临变化,但是对象又需要有效的管理

public enum country{
	china,
	japan,
	france,
	africa//改变
}

class sale{
	TaxBase tb;
	public void calculate(){
		if(tb == country.china){
			tb = country.japan;
		}else if(tb == country.japan){
			tb = country.france;
		}else if(tb == country.france){
			tb = country.france;
		}else if(tb == country.africa){
			tb = country.china;
			//改变
		}
	}
	
}

跟strategy模式非常相似的解决方法,只不过由于对象变化带来的“对象管理“变得复杂,所以运用上单例

class TaxState{
	private TaxState taxState;

	protected TaxState getTaxState(){ return this.taxState; }
	protected double calculate(){}
}

class ChinaTax{

	private ChinaTax chinaTax;
	
	public ChinaTax getInstance(){
		if(taxState==null){
			chinaTax=new ChinaTax();
		}
		return this.chinaTax;
	}
	
	@Override
	protected double calculate(){
		...
		super.setTaxState(JapanTax.getInstance());
	}
}

class JapanTax{
	
	private JapanTax japanTax;
	
	public JapanTax getInstance(){
		if(taxState==null){
			japanTax=new JapanTax();
		}
		return this.japanTax;
	}
	
	@Override
	protected double calculate(){
		...
		super.setTaxState(FranceTax.getInstance());
	}
}

//做一个对外的接口
class TaxStateProcess{

	TaxState ts;

	public double calculate(){
		ts.calculate();
		ts=ts.getTaxState();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值