如果观察者数量有许多,有人需要接受下雨通知,有人需要下雪,有人需要晴天,该如何来设计,肯定不能在目标借口写逻辑了
如果观察者数量有许多,有人需要接受下雨通知,有人需要下雪,有人需要晴天,该如何来设计,肯定不能在目标借口写逻辑了,
如果观察者数量有许多,有人需要接受下雨通知,有人需要下雪,有人需要晴天,该如何来设计,肯定不能在目标借口写逻辑了,
2018-01-10
观察者:
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的广播仍然存在,但在用户端过滤了。
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); } }
举报