如果观察者数量有许多,有人需要接受下雨通知,有人需要下雪,有人需要晴天,该如何来设计,肯定不能在目标借口写逻辑了,
观察者:
com.lone.watcherlombok.lombok.java.util.function.BiConsumerWeatherObserver Observer { String BiConsumer<WeatherSubjectWeatherObserver> (Subject subject) { (!(subject WeatherSubject)) { IllegalArgumentException()} .accept((WeatherSubject) subject)} }
测试:
com.lone.watchercom.lone.watcher.WeatherSubject.Statelombok.extern.slf4j.Main { (String[] args) { Observer girlfriend = WeatherObserver((subjectobserver) -> { State state = subject.getSubjectState()(State.== state) { .info(observer.getName()subject.getContent())} })Observer mother = WeatherObserver((subjectobserver) -> { State state = subject.getSubjectState()(State.== state || State.== state) { .info(observer.getName()subject.getContent())} })WeatherSubject subject = WeatherSubject()subject.attach(girlfriend) .attach(mother)subject.setSubjectState(State.)subject.setContent()} }
可否这样写,用户自定义自己的行为,Subject的广播仍然存在,但在用户端过滤了。
实际订阅者 肯定是在数据库里面的 根据订阅者订阅的天气分类等 查出 订阅者进行发布
定义三个observer列表~
其实就下雨下雪晴天等等这些信息,是来源于数据,即来自己被观察者的依赖。通常是交给第三方类处理。
设计一种数据结构,方便用户订阅和系统反馈
public class WheatherSubject { private List<WheatherObserver> mObservers = new ArrayList<>(); private String wheather; public final static String SNOW = "下雪"; public final static String RAIN = "下雨"; public final static String SUNNY = "晴"; public String getWheather() { return wheather; } public void setWheather(String wheather) { this.wheather = wheather; notifyObservers(wheather); } public void attach(WheatherObserver observer) { mObservers.add(observer); } public void detach(WheatherObserver observer) { mObservers.remove(observer); } public void notifyObservers(String wheather) { for (WheatherObserver observer : mObservers) { if (observer.getWheathers().size() < 1 || observer.getWheathers().contains(wheather)) { observer.update(wheather); } } } }
public class WheatherObserver { private ArrayList<String> mWheathers; public WheatherObserver(String... wheathers) { mWheathers = new ArrayList<>(); mWheathers.addAll(Arrays.asList(wheathers)); } public ArrayList<String> getWheathers() { return mWheathers; } public void setWheathers(ArrayList<String> wheathers) { if (mWheathers != null) { mWheathers.clear(); mWheathers.addAll(wheathers); } } public void update(String wheather){ System.out.print(wheather); Log.i("fy",wheather); } }
public class WheaterClint { public static void main(String[] args){ WheatherSubject subject = new WheatherSubject(); WheatherObserver observerAll = new WheatherObserver(); WheatherObserver observerSnow = new WheatherObserver(WheatherSubject.SNOW); WheatherObserver observerSnowAndRain = new WheatherObserver(WheatherSubject.SNOW,WheatherSubject.RAIN); subject.attach(observerAll); subject.attach(observerSnow); subject.attach(observerSnowAndRain); subject.setWheather(WheatherSubject.RAIN); } }