zoukankan      html  css  js  c++  java
  • 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();
    	}
    }
    

      

    三、运行结果

  • 相关阅读:
    webpack 命令行 传入自定义变量
    PHP 装饰器模式
    php图片合成【png图片】
    Sublime Text 3.1 3170 / 3176 注册码(附降级与禁止更新方法)
    菜鸟教程jsonp基础知识讲解
    CentOS7用yum安装软件提示 cannot find a valid baseurl for repobase7x86_64
    PHP的parse_ini_file()函数,解释结构类型php.ini格式的文件
    scp命令详解
    php常用错误码的意思
    php模式设计之 适配器模式
  • 原文地址:https://www.cnblogs.com/shamgod/p/4588557.html
Copyright © 2011-2022 走看看