```java public class MyTopic implements Subject { private List observers; private String message; private boolean changed; private final Object MUTEX = new Object();
public MyTopic() { this.observers = new ArrayList<>(); }
@Override public void register(Observer obj) { if (obj == null) throw new NullPointerException("Null Observer"); synchronized (MUTEX) { if (!observers.contains(obj)) observers.add(obj); } }
```java public class MyTopicSubscriber implements Observer { private String name; private Subject topic;
public MyTopicSubscriber(String name) { this.name = name; }
@Override public void update() { String msg = (String) topic.getUpdate(this); if (msg == null) { System.out.println(name + ":: No new message"); } else { System.out.println(name + ":: Consuming message::" + msg); } }
// 其他方法省略... } ```
### 测试示例
下面是一个简单的测试程序,演示如何使用上述实现。
```java public class ObserverPatternTest { public static void main(String[] args) { MyTopic topic = new MyTopic(); Observer obj1 = new MyTopicSubscriber("Obj1"); Observer obj2 = new MyTopicSubscriber("Obj2"); Observer obj3 = new MyTopicSubscriber("Obj3");