设计模式之Observer

相关概念:监听器 事件

问题:

模拟下列情形

•小孩在睡觉
•醒来后要求吃东西

设计一:

Dad不断轮训Child是否醒,若醒则喂他

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

class Child implements Runnable{
	private boolean wakenUp = false;

	public void wakeUp() {
		this.wakenUp = true;
	}

	public void setWakenUp(boolean wakenUp) {
		this.wakenUp = wakenUp;
	}

	public boolean isWakenUp() {
		return wakenUp;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			Thread.sleep(5000);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		this.wakeUp();
	}
}

class Dad implements Runnable {
	Child c;

	public Dad(Child c) {
		super();
		this.c = c;
	}
	
	public void feedChild() {
		System.out.println("feed child");
	}
	
	@Override
	public void run() {
		while(!c.isWakenUp()) {
			try {
				Thread.sleep(1000);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		this.feedChild();
	}

}

设计二:

Child醒了叫Dad喂他

package org.gui.oosd;

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

class Child implements Runnable {
	private boolean wakenUp = false;
	private Dad dad;

	public Child(Dad dad) {
		this.dad = dad;
	}

	public void wakeUp() {
		this.wakenUp = true;
		this.dad.feedChild();
	}

	public void setWakenUp(boolean wakenUp) {
		this.wakenUp = wakenUp;
	}

	public boolean isWakenUp() {
		return wakenUp;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			Thread.sleep(5000);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		this.wakeUp();
	}
}

class Dad {
	public void feedChild() {
		System.out.println("feed child");
	}

}


设计三:

使用事件,Child醒产生wakenUp事件,Dad等监听者处理事件

package com.bjsxt.dp.observer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;


class WakenUpEvent {
	private long time;
	private String loc;
	private Child source;
	
	public WakenUpEvent(long time, String loc, Child source) {
		super();
		this.time = time;
		this.loc = loc;
		this.source = source;
	}
	public long getTime() {
		return time;
	}
	public void setTime(long time) {
		this.time = time;
	}
	public String getLoc() {
		return loc;
	}
	public void setLoc(String loc) {
		this.loc = loc;
	}
	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 l) {
		wakenUpListeners.add(l);
	}
	
	void wakeUp() {
		for(int i=0; i<wakenUpListeners.size(); i++) {
			WakenUpListener l = wakenUpListeners.get(i);
			l.actionToWakenUp(new WakenUpEvent(System.currentTimeMillis(), "bed", this));
		}
	}

	public void run() {
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		this.wakeUp();
	}
	
}

class Dad implements WakenUpListener {

	public void actionToWakenUp(WakenUpEvent wakenUpEvent) {
		System.out.println("feed child");
	}
	
}

class GrandFather implements WakenUpListener {

	public void actionToWakenUp(WakenUpEvent wakenUpEvent) {
		System.out.println("hug child");
	}
	
}

class Dog implements WakenUpListener {

	public void actionToWakenUp(WakenUpEvent arg0) {
		System.out.println("wang wang ...");
	}
	
}

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

public class Test {
	public static void main(String[] args) {
		Child c = new Child();
		
		
		String[] observers = PropertyMgr.getProperty("observers").split(",");

		for(String s : observers) {
			try {
				c.addWakenUpListener((WakenUpListener)(Class.forName(s).newInstance()));
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
		
		
		new Thread(c).start();
	}
}
//思考PropertyMgr类所涉及的单例模式和缓存
class PropertyMgr {
	private static Properties props = new Properties();
	
	static {
		try {
			props.load(Test.class.getClassLoader().getResourceAsStream("observer.properties"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static String getProperty(String key) {
		return props.getProperty(key);
	}
}

class CryEvent {
}

abstract class Event {

}

observers.properties

observers=org.gui.dp.observer.Dad,org.gui.dp.observer.GrandFather,org.gui.dp.observer.Dog

AWT模拟:

package org.gui.dp.observer.awt;

import java.awt.Button;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

@SuppressWarnings("serial")
public class TestFrame extends Frame {
	public void launch() {
		Button b = new Button("press me");
		b.addActionListener(new MyActionListener());
		b.addActionListener(new MyActionListener2());
		this.add(b);
		this.pack();

		this.addWindowListener(new WindowAdapter() {

			@Override
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}

		});

		this.setVisible(true);
	}

	public static void main(String[] args) {
		new TestFrame().launch();
	}

	private class MyActionListener implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			System.out.println("button pressed!");
		}

	}

	private class MyActionListener2 implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			System.out.println("button pressed 2!");
		}

	}
}


package org.gui.dp.observer.awt;

import java.util.ArrayList;
import java.util.List;

public class Test {
	public static void main(String[] args) {
		Button b = new Button();
		b.addActionListener(new MyActionListener());
		b.addActionListener(new MyActionListener2());
		b.buttonPressed();
	}
}

class Button {
	private List<ActionListener> actionListeners = new ArrayList<ActionListener>();
	
	public void buttonPressed() {
		ActionEvent event = new ActionEvent(System.currentTimeMillis(), this);
		for (ActionListener l : actionListeners) {
			l.actionPerformed(event);
		}
	}

	public void addActionListener(ActionListener listener) {
		this.actionListeners.add(listener);
	}
	
}

interface ActionListener {

	public void actionPerformed(ActionEvent event);
	
}

class MyActionListener implements ActionListener {

	@Override
	public void actionPerformed(ActionEvent event) {
		System.out.println("button pressed");
	}
	
}

class MyActionListener2 implements ActionListener {

	@Override
	public void actionPerformed(ActionEvent event) {
		System.out.println("button pressed2");
	}
	
}

class ActionEvent {
	long when;
	Object source;
	
	public ActionEvent(long when, Object source) {
		super();
		this.when = when;
		this.source = source;
	}

	public long getWhen() {
		return System.currentTimeMillis();
	}
	
	public void setWhen(long when) {
		this.when = when;
	}

	public Object getSource() {
		return null;
	}
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值