状态模式实现电控门的开关(java)

目录:一个实例讲完23种设计模式

当前:状态模式-电控门-java

关联:状态模式-坦克大战-java

需求

动作 开门状态 关门状态 动作后的状态
不反应 开门 开门状态
关门   不反应 关门状态

代码


class Function{
	public String mStr;
	Function(String str){
		mStr = str;
		exe();
	}
	public void exe() {
		System.out.println(mStr);
	}
};
interface IState{
	void open();
	void close();
}

class OpenState implements IState{
	public void open() {}
	public void close() {
		new Function("closed");
		Door.mState = new CloseState();
	}
}
class CloseState implements IState{
	public void open() {
		new Function("opend");
		Door.mState = new OpenState();
	}
	public void close() {}
}
class Door{
	static IState mState = new CloseState();
	public void open() {
		mState.open();
	}
	public void close() {
		mState.close();
	}
}

public class Client {
	public static void main(String[] args) {
		System.out.println("hello worldff !");
		Door d = new Door();
		System.out.println("client close");
		d.close();
		System.out.println("client open");
		d.open();
		System.out.println("client open2");
		d.open();
		System.out.println("client close2");
		d.close();
	}
}

 

 

 

你可能感兴趣的:(设计模式-坦克大战-java)