Q:观察者模式属于哪一类设计模式
A:观察者模式属于行为学模式
Q:什么是观察者模式
A:当一个对象的状态发生改变时,所有依赖它的对象都得到通知,并自动更新
观察者模式解析:报纸类维护了一个订阅者数组,我们可以通过报纸类遍历订阅者数组来通知所有订阅者
订阅者类
public interface Subscriber { void update(String message); }
订阅者实现类
public class SubscriberImpl implements Subscriber {private String name;@Overridepublic void update(String message) {System.out.println(name + "---接收到消息:" + message);}
}
报纸类
public interface NewsPaper {void addSubscriber(Subscriber subscriber);//添加订阅者void removeSubscriber(Subscriber subscriber);//移除订阅者void notifySubscriber(String message);//通知订阅者
}
报纸实现类
public class NewsPaperImpl implements NewsPaper {private List<Subscriber> subscribers = new ArrayList<>();@Overridepublic void addSubscriber(Subscriber subscriber) { subscribers.add(subscriber); }@Overridepublic void removeSubscriber(Subscriber subscriber) { subscribers.remove(subscriber); }@Overridepublic void notifySubscriber(String message) {for (Subscriber s : subscribers) {s.update(message);}}
}
演示类
public class Demo {public static void main(String[] args) {NewsPaperImpl newsPaper = new NewsPaperImpl();SubscriberImpl subscriber1 = new SubscriberImpl("李老头");SubscriberImpl subscriber2 = new SubscriberImpl("王奶奶");newsPaper.addSubscriber(subscriber1);newsPaper.addSubscriber(subscriber2);newsPaper.notifySubscriber("今天的报纸收到了!");newsPaper.removeSubscriber(subscriber1);newsPaper.notifySubscriber("明天的报纸还是这个点到!");}
}
演示结果