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

      

    三、运行结果

  • 相关阅读:
    golang-cron定时任务
    卡特兰数
    树的直径
    虚拟机之Hyper-V
    tag of loj
    wx.requestSubscribeMessage无法弹窗,显示20001报错?
    nginx日志切割
    小程序首次加载过慢以及点击微信授权不弹出授权框的问题
    外网访问小程序显示网络错误问题以及总是走wx.request里面的fail回调问题
    http转https以及ssl证书配置以及安装
  • 原文地址:https://www.cnblogs.com/shamgod/p/4588557.html
Copyright © 2020-2023  润新知