ITPub博客

首页 > Linux操作系统 > Linux操作系统 > observer

observer

原创 Linux操作系统 作者:spring7777777 时间:2009-01-07 15:03:11 0 删除 编辑
 

NewsPapers

public interface NewsPapers {

   

    public void add(Customers observer);

   

    public void remove(Customers observer);

   

    public void notifyObserver();

 

}

 

 

ConcreteNewsPapers

public class ConcreteNewsPapers implements NewsPapers {

   

    private Vector observerVector = new Vector();

 

    public void add(Customers observer) {

 

       System.out.println(" 添加一个订阅者 ");

       observerVector.add(observer);

    }

 

    public void notifyObserver() {

       // TODO Auto-generated method stub

       Enumeration em = observerVector.elements();

       while(em.hasMoreElements()){

          

           ((Customers)em.nextElement()).update();

          

       }

      

    }

 

    public void remove(Customers observer) {

       // TODO Auto-generated method stub

       System.out.println(" 删除一个订阅者 ");

       observerVector.remove(observer);

 

    }

 

}

 

Customers

public interface Customers {

 

    public void update();

}

 

Customers的实现类们:

public class ConcreteCustomer implements Customers {

 

    public void update() {

       // TODO Auto-generated method stub

       System.out.println(" I'm customer , notify!");

 

    }

 

}

 

public class ConcreteCustomerB implements Customers {

 

    public void update() {

       // TODO Auto-generated method stub

       System.out.println(" I'm customer b, notify!");

 

    }

 

}

测试类;

 

public class ObserverTest extends TestCase {

   

    public void test_adapter(){

       

       //主题

        NewsPapers news = new ConcreteNewsPapers();

        //观察者

        Customers customer = new ConcreteCustomer();

        Customers customerB = new ConcreteCustomerB();

        Customers customerC = new ConcreteCustomerC();

       

        news.add(customer);

        news.add(customerB);

       

        news.notifyObserver();

        //添加 c

        news.add(customerC);

       

        news.notifyObserver();

       

    }

 

}

 

测试结果:

 

添加一个订阅者

 添加一个订阅者

 I'm customer , notify!

 I'm customer b, notify!

 添加一个订阅者

 I'm customer , notify!

 I'm customer b, notify!

 I'm customer C, notify!

 

observer.jpg

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/11134734/viewspace-531642/,如需转载,请注明出处,否则将追究法律责任。

下一篇: Singleton
请登录后发表评论 登录
全部评论

注册时间:2008-06-10

  • 博文量
    49
  • 访问量
    96611