`

题目----猫叫---设计模式

阅读更多
题目:猫大叫一声,所有的老鼠都开始逃跑,主人被惊醒 
要求:
1.要有联动性,老鼠和主人的行为是被动的
2.考虑可扩展性,猫的叫声可能引起其他联动效应
下面是自己写的:
哈哈。设计模式学得还不错。。。。。

public class Cat {
	List<Hearable> hearers = new ArrayList<Hearable>();
	
	public void addObserver(Hearable h){
		hearers.add(h);
	}
	
	public void removeOberver(Hearable h){
		hearers.remove(h);
	}
	
	public void call(){
		for(Hearable h : hearers){
			h.doAfterHear();
		}
	}
}

public interface Hearable {
	public void doAfterHear();
}

public class Master implements Hearable{
	
	 Status status;
	 
	 public Master(){
		 status = Status.SLEEP;
	 }
	 
	 public void frighten(){
		 status = Status.WAKEUP;
		 System.out.println("我是主人,我被你这该死的猫吵醒了");
	 }

	public Status getStatus() {
		return status;
	}
	public void doAfterHear(){
		frighten();
	}

}

enum Status {
	SLEEP,WAKEUP;

	@Override
	public String toString() {
		String s = "";
		switch(this){
		case SLEEP:s = "sleep";break;
		case WAKEUP :s= "wakeup" ;break;
		default:s = "没有匹配项";
		}
		return s;
	}

}

public class Mouse implements Hearable{
	
	public void doAfterHear() {
		flee();
		
	}

	public static final int STOP = 0;
	public static final int ESCAPE = 1;
	
	private int nameCode;
	
	private int status;
	
	public Mouse(int nameCode){
		status = STOP;
		this.nameCode = nameCode;
	}

	public int getStatus() {
		return status;
	}
	
	public void flee(){
		System.out.println("我是老鼠"+nameCode+" 我在逃跑");
	}
	
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics