⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mouseandcat.java

📁 几个设计模式的java源码实例
💻 JAVA
字号:
/*
*	半夜了,老鼠出来活动,通知猫去抓老鼠。。。
*	用观察者模式实现上述场景(Google笔试)
*   老鼠为主题,猫为观察者,时间触发老鼠活动通知猫
*/
package MouseAndCat;
import java.util.*;

class Mouse{
	Mouse(String n){
		catList = new ArrayList();
		this.name = n;
	}
	public void register(Cat cat){
		catList.add(cat);
	}
	public void remove(Cat cat){
		int index = catList.indexOf(cat);
		if(index>=0){
			catList.remove(index);
		}
	}
	public void notifyCats(){
		for(int i=0; i<catList.size(); i++){
			Cat cat = (Cat)catList.get(i);
			cat.action();
		}
	}
	public void timeToPlay(){
		this.notifyCats();
	}
	private String name;
	private ArrayList catList;
}

class Cat{
	Cat(String n, Mouse m){
		name = n;
		mouse = m;
		this.mouse.register(this);
	}
	public void action(){
		System.out.println("Cat "+name+" is waking up");
	}
	private String name;
	private Mouse mouse;
} 
public class MouseAndCat {
	public static void main(String[] args) {
		Mouse mouse = new Mouse("mickey");
		Cat cat1 = new Cat("cat1", mouse);
		Cat cat2 = new Cat("cat2", mouse);
		Cat cat3 = new Cat("cat3", mouse);
		mouse.timeToPlay();
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -