状态模式允许对象在内部状态发生改变时改变它的行为,对象看起来好像修改了它的类。主要解决对象的行为依赖于它的状态(属性),并且可以根据它的状态改变而改变它的相关行为。
示例如下(水随温度改变状态):
创建一个接口state
package H2O;
public interface State {
public abstract void show();
}
三个具体类实现state接口
public class IceState implements State{
public void show() {
// TODO Auto-generated method stub
System.out.println("此时为固态");
}
}
public class LiquidState implements State{
public void show() {
// TODO Auto-generated method stub
System.out.println("此时为液态");
}
}
public class GaseousState implements State {
public void show() {
// TODO Auto-generated method stub
System.out.println("此时为汽态");
}
}
当前状态
public class H2O {
State Icestate,Liquidstate,Gaseousstate,state;
double tem;
H2O(){
this.tem = tem;
Icestate = new IceState();
Liquidstate = new LiquidState();
Gaseousstate = new GaseousState();
state = Liquidstate;//初始为液态
}
void changeTemperature(double temperature){
this.tem = temperature;
state.show();
if(state==Liquidstate){
if(temperature>=100){
state=Gaseousstate;
System.out.println("变为汽态");
}
if(temperature<=0){
state=Icestate;
System.out.println("变为固态");
}
if((temperature<100) &(temperature>0)){
System.out.println("仍为液态");
}
}
else if(state==Gaseousstate){
if(temperature>=100){
System.out.println("仍为汽态");
}
if(temperature<=0){
state=Icestate;
System.out.println("凝华变为固态");
}
if((temperature<100) &(temperature>0)){
state=Liquidstate;
System.out.println("变为液态");
}
}
else if(state==Icestate){
if(temperature>=100){
state=Gaseousstate;
System.out.println("汽化变为汽态");
}
if(temperature<=0){
state=Icestate;
System.out.println("仍为固态");
}
if((temperature<100) &(temperature>0)){
state=Liquidstate;
System.out.println("变为液态");
}
}
}
public void changeLiquid(){
state=Liquidstate;
}
public void changGaseous(){
state=Gaseousstate;
}
public void changeIce(){
state=Icestate;
}
}
实现类
public class Application {
public static void main(String args[]){
H2O h2o=new H2O();
h2o.changeTemperature(0);
System.out.println("温度为"+h2o.tem);
h2o.changeTemperature(70);
System.out.println("温度为"+h2o.tem);
h2o.changeTemperature(155);
System.out.println("温度为"+h2o.tem);
}
}
结果
状态模式可以用来取代if else语句判断,使得代码变得简洁明了,但是局限性较大,适合范围有限,仅适合一些结构简单的场景。