• 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();
    	}
    }
    

      

    三、运行结果

  • 相关阅读:
    input 控制输入非负数
    查看web项目中的.class文件的路径
    web(获取路径的方法)
    javascript从入门到精通(三)
    javascript从入门到精通(二)
    javascript从入门到精通(一)
    jquery从入门到精通(一)
    background-sizi (转)
    background-position (转)
    html,css命名规范 (转)
  • 原文地址:https://www.cnblogs.com/shamgod/p/4588557.html
Copyright © 2020-2023  润新知