• 设计模式 观察者模式


    首先写秘书类

    import java.util.ArrayList;
    import java.util.List;
    
    public class Secretary {
    
    	private List<StockObserver> observers=new ArrayList<StockObserver>();
    	
    	private String action;
    	
    	public String getAction() {
    		return action;
    	}
    
    	public void setAction(String action) {
    		this.action = action;
    	}
    
    	public void Attach(StockObserver observer)
    	{
    		observers.add(observer);
    	}
    	
    	public void Notify()
    	{
    		for (StockObserver stockObserver : observers) {
    			stockObserver.Update();
    		}
    	}
    	
    	
    }
    

    在写观察者类

    
    public class StockObserver {
    
    	private String name;
    	private Secretary sub;
    	public StockObserver(String name,Secretary sub)
    	{
    		this.name=name;
    		this.sub=sub;
    	}
    	public void Update()
    	{
    		System.out.println(sub.getAction()+"!!!"+name+"关闭股票行情,继续工作!");
    	}
    }
    
    

    在写测试类

    
    public class Program {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Secretary secretary=new Secretary();
    		StockObserver worker1 = new StockObserver("施于任", secretary);
    		StockObserver worker2 = new StockObserver("魏国冲", secretary);
    		
    		//登记着两位工友
    		secretary.Attach(worker1);
    		secretary.Attach(worker2);
    		
    		//发现老板回来
    		secretary.setAction("老板回来了");
    		
    		//通知两个同事
    		secretary.Notify();
    	}
    
    }
    
    
  • 相关阅读:
    监控里的主码流和子码流是什么意思
    监控硬盘容量计算
    一个能让你了解所有函数调用顺序的Android库
    电工选线
    oracle linux dtrace
    list all of the Oracle 12c hidden undocumented parameters
    Oracle Extended Tracing
    window 驱动开发
    win7 x64 dtrace
    How to Use Dtrace Tracing Ruby Executing
  • 原文地址:https://www.cnblogs.com/yufenghou/p/6035359.html
Copyright © 2020-2023  润新知