Java中观察者模式(Observer)_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Java中观察者模式(Observer)

Java中观察者模式(Observer)

 2018/10/18 9:45:42  andrew7676  程序员俱乐部  我要评论(0)
  • 摘要:1.Java中Observer观察者模式publicinterfaceWatched{publicvoidaddWatcher(Watcherwatcher);publicvoidremoveWatcher(Watcherwatcher);publicvoidnotifyWatchers(Stringstr);}publicinterfaceWatcher{publicvoidupdate(Stringstr);
  • 标签:Server Java 模式 观察者模式
1. Java中Observer观察者模式
class="Watched.java" name="code">
public interface Watched{
    public void addWatcher(Watcher watcher);
    public void removeWatcher(Watcher watcher);
    public void notifyWatchers(String str);
}

public interface Watcher{
    public void update(String str);
}

public class ConcreteWatched implements Watched{
    private List<Watcher> list = new ArrayList<Watcher>();
    @Override
    public void addWatcher(Watcher watcher){
        list.add(watcher);
    }
    @Override
    public void removeWatcher(Watcher watcher){
        list.remove(watcher);
    }
    @Override
    public void notifyWatchers(String str){
        for(Watcher watcher : list){
            watcher.update(str);
        }
    }
}

public class ConcreteWatcher implements Watcher{
    @Override
    public void update(String str){
        System.out.println(str);
    }
}

public class Test{
    public static void main(String[] args){
        Watched girl = new ConcreteWatched();
        
        Watcher watcher1 = new ConcreteWatcher();
        Watcher watcher2 = new ConcreteWatcher();
        Watcher watcher3 = new ConcreteWatcher();
        girl.addWatcher(watcher1);
        girl.addWatcher(watcher2);
        girl.addWatcher(watcher3);
        
        girl.notifyWatchers("开心,爽");
        girl.removeWatcher(watcher2);
        girl.notifyWatchers("不爽");
    }
}

发表评论
用户名: 匿名