[原创]设计模型探索C3-Observer parttern 之饲机而动

[原创]设计模型探索C3-Observer parttern 之饲机而动
观察者JDK实现:
1.主题
package  observer.jdk;

import  java.util.Observable;

public   class  SubjectImpl  extends  Observable
{   
    
public void notifying()
    
{
        
this.setChanged();
        
this.notifyObservers("重要通知");
    }

}



2.观察者
package  observer.jdk;

import  java.util.Observable;
import  java.util.Observer;

public   class  ObserverImpl  implements  Observer
{   
    
private String name;
    
    
public ObserverImpl(String name)
    
{
        
this.name = name;
    }


    
public void update(Observable o, Object arg)
    
{
        System.out.println(
this.name + "观察者收到:\"" + arg + "\"");
    }

}


3.测试类
package  observer.jdk;


public   class  Test
{   
    
public static void main(String[] args)
    
{
        SubjectImpl subject 
= new SubjectImpl();
        
        subject.addObserver(
new ObserverImpl("小赵"));
        subject.addObserver(
new ObserverImpl("小钱"));
        subject.addObserver(
new ObserverImpl("小孙"));
        subject.addObserver(
new ObserverImpl("小李"));
        
        subject.notifying();
        
    }

}

你可能感兴趣的:([原创]设计模型探索C3-Observer parttern 之饲机而动)