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

      

    三、运行结果

  • 相关阅读:
    python 获取当前文件夹下所有文件名
    leetcode 205. Isomorphic Strings
    leetcode 204. Count Primes
    leetcode 203. Remove Linked List Elements
    神经网络中的激活函数tanh sigmoid RELU softplus softmatx
    leetcode 189. Rotate Array
    一个简单的二进制加法器
    AliOS编译安装MyRocks
    MYSQL5.7无法启动服务原因及解决方案
    基础知识巩固笔记(链接、装载与库)
  • 原文地址:https://www.cnblogs.com/shamgod/p/4588557.html
Copyright © 2011-2022 走看看