首页 > 代码库 > 观察者模式

观察者模式

定义:

对象之间存在一对多的关系,一的一方(被依赖对象,一般为Subject)变化,通知多的一方(依赖对象,一般为ObServer)。

UML:

技术分享

代码实现例子:

public interface ISubject {
    public void registerObServer(IObserver iObserver);
    public void removeObServer(IObserver iObserver);
    public void notifyObServers();
}


public class ConcreteSubject implements ISubject {
    List<IObserver> data = http://www.mamicode.com/new ArrayList<IObserver>();
    Message msgObj = null;

    @Override
    public void registerObServer(IObserver iObserver) {
        data.add(iObserver);
    }

    @Override
    public void removeObServer(IObserver iObserver) {
        if (data.contains(iObserver)) {
            data.remove(iObserver);
        }
    }

    @Override
    public void notifyObServers() {
        for (int i = 0; i < data.size(); i++) {
            IObserver ob = data.get(i);
            ob.update(msgObj);
        }
    }

    public void createMessage(String msg) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        msgObj = new Message(msg, df.format(new Date()));
    }

    public class Message {
        String message = null;
        String time = null;

        public Message(String msg, String time) {
            this.message = msg;
            this.time = time;
        }

        public String getMessage() {
            return this.message;
        }

        public String getTime() {
            return this.time;
        }
    }
}


public interface IObserver {
    void update(Object obj);//订阅端获取到通知后处理逻辑

}

public class ObserverA implements IObserver {

    @Override
    public void update(Object obj) {
        Message msg = (Message) obj;
        doThings(msg);

    }

    public void doThings(Message msg) {
      System.out.println("我是A,我在时间:"+msg.getTime()+",接收到订阅消息:"+msg.getMessage());
    }

}

public class ObserverB implements IObserver {

    @Override
    public void update(Object obj) {
        Message msg = (Message) obj;
        doThings(msg);

    }

    public void doThings(Message msg) {
      System.out.println("我是B,我在时间:"+msg.getTime()+",接收到订阅消息:"+msg.getMessage());
    }

}



public class test {
    public static void main(String[] args) {
        IObserver A=new ObserverA();
        IObserver B=new ObserverB();
        ConcreteSubject subject=new ConcreteSubject();
        subject.registerObServer(A);
        subject.registerObServer(B);
        subject.createMessage("这是第一条消息");
        subject.notifyObServers();

      
    }

}

 

观察者模式