zoukankan      html  css  js  c++  java
  • java: 观察者模式:Observable被观察者,Observer观察者

    java: 观察者模式:Observable被观察者,Observer观察者

    以房子价格为例,卖房者为被观察者:

    import java.util.Observable;
    
    //被观察者子类化
    public class House extends Observable {
    
    	private float price;
    	
    	public House(float price)
    	{
    		this.price = price;
    	}
    
    	public float getPrice() {
    		return price;
    	}
    
    	public void setPrice(float price) {
    		//通知内容已经被修改
    		super.setChanged();
    		//一旦价格修改成功,那么应该通知观察者
    		this.price = price;
    		//通知所有观察者
    		super.notifyObservers(price);
    	}
    	
    	public String toString()
    	{
    		return "房子";
    	}
    	
    	
    	
    
    }
    

      

    买房者为观察者:

    import java.util.Observable;
    import java.util.Observer;
    
    //实现观察者接口
    public class Person implements Observer {
    
    	@Override
    	public void update(Observable o, Object arg) {
    		// TODO 自动生成的方法存根
    		
    		//当被观察者发生变化,观察者立马能接受都信息
    		System.out.println( o + " ****** 房子的价格已经发生改变" + arg);
    		
    	}
    
    }
    

      

    实例被观察者,与观察者:

    public class ObserverDemo {
    
    	public static void main(String[] args) {
    		// TODO 自动生成的方法存根
    
    		//实例化被观察者
    		House h = new House(3000.00f);
    		
    		//实例化观察者
    		Person p1 = new Person();
    		Person p2 = new Person();
    		Person p3 = new Person();
    		
    		//增加观察者
    		h.addObserver(p1);
    		//增加观察者
    		h.addObserver(p2);
    		//增加观察者
    		h.addObserver(p3);
    		
    		//被观察者价格发生改变
    		h.setPrice(4000.00f);
    		
    	}
    
    }
    

      

  • 相关阅读:
    [C++] split string by string
    工作三个月心得经验
    Ubuntu Command-Line: Enable Unlimited Scrolling in the Terminal
    What is the PPA and How to do with it ?
    WCF vs ASMX WebService
    The ShortCuts in the ADT (to be continued)
    when does the View.ondraw method get called
    Browsing Storage Resources with Server Explorer
    Get start with Android development
    C++ Frequently asking question
  • 原文地址:https://www.cnblogs.com/achengmu/p/7006952.html
Copyright © 2011-2022 走看看