状态模式-马士兵设计模式教程

//表示状态的接口类
public interface State {
	void smile();
	void cry();
	void say();
}

//高兴的状态
public class HappyState implements State{
	@Override
	public void cry() {
		System.out.println("高兴的哭");
	}
	@Override
	public void say() {
		System.out.println("高兴的说");
	}
	@Override
	public void smile() {
		System.out.println("高兴的笑");
	}
}

//不高兴的状态
public class UnHappyState implements State{
	@Override
	public void cry() {
		System.out.println("伤心的哭");
	}
	@Override
	public void say() {
		System.out.println("不高兴的说");
	}
	@Override
	public void smile() {
		System.out.println("不高兴的笑");
	}
}

public class MM{
	private State state = new HappyState();//在这里的状态决定了mm的行为
	private String name;
	public MM(State state){//可以在外部传递mm的状态
		this.state=state;
	}
	public MM(){}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void cry() {
		state.cry();
	}
	public void say() {
		state.say();
	}
	public void smile() {
		state.smile();
	}
}

public class Test {
	public static void main(String[] args) {
		MM mm = new MM(new HappyState());
		mm.cry();
		MM mm1=new MM(new UnHappyState());
		mm1.cry();
		/**
		 * 运行结果:
		 * 高兴的哭
		 * 伤心的哭
		 */
	}
}

你可能感兴趣的:(状态模式-马士兵设计模式教程)