package com.iit.observer; //研究性的作业: //业务场景:(到了吃饭时间)管理员就调用sendMsg方法, // 需要向Cat和Dog发送一条消息。 //发布,关注(订阅):Cat和Dog关注了张三这个Person;当Person有活动时,就要能够通知Cat和Dog。 public class Person { private Cat cat; //缺点:增加需要通知的成员,改动量比较大。 private Cat cat2; private Cat cat3; private Dog dog; public Person(Cat cat,Dog dog){ this.cat = cat; this.dog = dog; } public void sendMsg(String msg){ this.cat.update(msg); this.dog.update(msg); } public static void main(String[] args) { Cat cat = new Cat(); Dog dog = new Dog(); Person p = new Person(cat,dog); p.sendMsg("吃鱼.."); } } class Cat{ public void update(String msg){ System.out.println("cat收到:"+msg); System.out.println("cat:慢慢吃..."); } } class Dog{ public void update(String msg){ System.out.println("dog收到:"+msg); System.out.println("dog:大口吃..."); } }
搜索
复制
标签:找出,场景,dog,cat,Person,Dog,msg,Cat,设计模式 From: https://www.cnblogs.com/xiaoyongdata/p/16591671.html