动机:对象的状态经常面临变化,但是对象又需要有效的管理
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();
}
}