zoukankan      html  css  js  c++  java
  • 观察者模式(一)

    1.两种角色

    观察者和被观察者

    2.被观察者的类实现了如下方法;

      a。对观察者的管理,  删除添加观察者

      b. 状态的变化:设置和获得状态是否变化

       c。通知观察者

    3.对于观察者:

    在收到被观察者的通知后,做通知后的事情

     1 package yinyong;
     2 
     3 import java.util.Observable;
     4 import java.util.Observer;
     5 
     6 class Gupiao extends Observable
     7 {
     8     String name;
     9     int price;
    10     public Gupiao(String name,int price)
    11     {
    12         this.name=name;
    13         this.price=price;
    14         
    15     }
    16     public void setPrice(int price)
    17     {
    18         this.price=price;
    19         setChanged();
    20         notifyObservers(price);//通知各个观察者,参数为price
    21     }
    22     
    23 }
    24 class  GuMin implements Observer
    25  {
    26 
    27     
    28     public void update(Observable o, Object arg) {
    29         // TODO 自动生成的方法存根
    30         Gupiao gupiao=(Gupiao)o;
    31         System.out.println(gupiao.name+"  的价格变成"+arg);
    32         
    33         
    34     }
    35     }
    36 
    37 public class Test {
    38     public static void main(String args[])
    39     {
    40     Gupiao gupiao=new Gupiao("Lenvon",34);
    41     gupiao.addObserver(new GuMin());
    42     gupiao.setPrice(-3);
    43     gupiao.setPrice(34);
    44     
    45     }
    46     
    47     
    48         
    49         
    50         
    51                     
    52     
    53 }
  • 相关阅读:
    尚未为数据源“RptDataSet_StatEC”提供数据源实例
    C3P0的详细配置说明(com.mchange.v2.c3p0.comboPooledDataSource)
    TopCoder SRM 581
    [ZJOI2012]灾难
    Codeforces 313
    [ZJOI2010]数字计数
    [ZJOI2010]排列计数
    [ZJOI2009]函数
    [ZJOI2009]假期的宿舍
    [ZJOI2008]骑士
  • 原文地址:https://www.cnblogs.com/hansongjiang/p/3850024.html
Copyright © 2011-2022 走看看