设计模式---观察者模式

来源:互联网 发布:淘宝九块九包邮在哪 编辑:程序博客网 时间:2024/06/06 18:16

1. 观察者模式图

分析:

1. 所有观察者必须在目标对象中注册,这样目标对象才可以管理观察者对象的引用。

2. 目标对象需要提供增加和删除观察者的API,这是最基本的功能。

3. 目标对象中应该有个通知所有观察者的API,当目标对象处理某件事情的时候,应该将这种讯息传递给感兴趣的观察者。


2. 应用场景假设

有个女孩长得很漂亮,同时有三个男生在追求她,那么这三个男生肯定对这个女孩的一举一动非常的感兴趣。我们假设这个女孩是目标对象,

也就是被观察者,这三个男生就是观察者。


3. 项目结构


4. 接口层代码

package com.jack.inface;/** * 抽象观察者 * */public interface BoyWatcherInface {public void handlerEvent(EventInface event);}

package com.jack.inface;import java.util.ArrayList;import java.util.List;/** * 抽象被观察者(目标对象的抽象) * */public interface GirlTargetInface {List<BoyWatcherInface> list = new ArrayList<>();public void addWatch(BoyWatcherInface watcher);public void removeWatch(BoyWatcherInface watcher);public void notifyWatchs(EventInface event);}

package com.jack.inface;/** * 抽象事件 * */public interface EventInface {public String sayHello();public String sayRun();}

5. 实现层代码

package com.jack.inface.impl;import com.jack.inface.BoyWatcherInface;import com.jack.inface.EventInface;public class BoyWatcherInfaceImpl implements BoyWatcherInface {@Overridepublic void handlerEvent(EventInface event) {System.out.println(event.sayHello());System.out.println(event.sayRun());System.out.println("**************************************");}}

package com.jack.inface.impl;import com.jack.inface.BoyWatcherInface;import com.jack.inface.EventInface;import com.jack.inface.GirlTargetInface;public class GirlTargetInfaceImpl implements GirlTargetInface {@Overridepublic void addWatch(BoyWatcherInface watcher) {list.add(watcher);}@Overridepublic void removeWatch(BoyWatcherInface watcher) {list.remove(watcher);}@Overridepublic void notifyWatchs(EventInface event) {for(BoyWatcherInface watcher : list){watcher.handlerEvent(event);}}}

package com.jack.inface.impl;import com.jack.inface.EventInface;public class EventInfaceImpl implements EventInface {@Overridepublic String sayHello() {return "I want to say hello to all of you .";}@Overridepublic String sayRun() {return "I want to run in our school, do you want to go with me ?";}}

6. 测试

package com.jack.test;import com.jack.inface.BoyWatcherInface;import com.jack.inface.EventInface;import com.jack.inface.GirlTargetInface;import com.jack.inface.impl.BoyWatcherInfaceImpl;import com.jack.inface.impl.EventInfaceImpl;import com.jack.inface.impl.GirlTargetInfaceImpl;public class ModerDesignTest {public static void main(String[] args) {GirlTargetInface girl = new GirlTargetInfaceImpl();BoyWatcherInface boy1 = new BoyWatcherInfaceImpl();BoyWatcherInface boy2 = new BoyWatcherInfaceImpl();BoyWatcherInface boy3 = new BoyWatcherInfaceImpl();girl.addWatch(boy1);girl.addWatch(boy2);girl.addWatch(boy3);EventInface event = new EventInfaceImpl();girl.notifyWatchs(event);}}

7. 运行结果






0 0