Java-马士兵设计模式学习笔记-观察者模式-OOD 封装Listener

 一、概述

childe类中的是关联监听者dad的,若要再增加监听者,会很不方便,且要修改代码。好的方法是封装监听者类,用addListener()方法动态添加监听者

 

二、代码

1.Test.java

class WakenUpEvent{
	
	private long time;
	private String location;
	private Child source;
	
	public WakenUpEvent(long time, String location, Child source) {
		super();
		this.time = time;
		this.location = location;
		this.source = source;
	}

	public long getTime() {
		return time;
	}

	public void setTime(long time) {
		this.time = time;
	}

	public String getLocation() {
		return location;
	}

	public void setLocation(String location) {
		this.location = location;
	}

	public Child getSource() {
		return source;
	}

	public void setSource(Child source) {
		this.source = source;
	}
	
	
}

class Child implements Runnable {
	
	private List<WakenUpListener> wakenUpListeners = new ArrayList<WakenUpListener>();
	
	public void addWakenUpListener(WakenUpListener wul){
		wakenUpListeners.add(wul);
	}
	public void wakeUp(){
		for(int i = 0; i < wakenUpListeners.size(); i++){
			WakenUpListener l = wakenUpListeners.get(i);
			l.actionToWakenUp(new WakenUpEvent(System.currentTimeMillis(), "bed", this));
		}
	}

	@Override
	public void run() {
		try {
			Thread.sleep(3000);
		} catch (Exception e) {
			e.printStackTrace();
		}
		wakeUp();
	}
}


interface WakenUpListener {
	public void actionToWakenUp(WakenUpEvent e);
}

class Dad implements WakenUpListener {

	public void actionToWakenUp(WakenUpEvent e) {
		System.out.println("Fedd the child");
	}
	
}

class GrandFather implements WakenUpListener {

	public void actionToWakenUp(WakenUpEvent e) {
		System.out.println("抱孩子");
	}
	
}


public class Test {

	public static void main(String[] args) {
		Child c = new Child();
		c.addWakenUpListener(new Dad());
		c.addWakenUpListener(new GrandFather());
		new Thread(c).start();
	}
}

  

三、运行结果

posted @ 2015-06-19 14:34  shamgod  阅读(622)  评论(0编辑  收藏  举报
haha