大家好,又见面了,我是全栈君。
本文继续介绍23种设计模式系列之观察者模式。
public interface Watcher
{
public void update();
}
public interface Watched
{
public void addWatcher(Watcher watcher);
public void removeWatcher(Watcher watcher);
public void notifyWatchers();
}
具体的观察者
public class Security implements Watcher
{
@Override
public void update()
{
System.out.println(“运输车有行动,保安贴身保护");
}
}
public class Thief implements Watcher
{
@Override
public void update()
{
System.out.println(“运输车有行动,强盗准备动手");
}
}
public class Police implements Watcher
{
@Override
public void update()
{
System.out.println(“运输车有行动,警察护航");
}
}
public class Transporter 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();
}
}
}
public class Test
{
public static void main(String[] args)
{
Transporter transporter = new Transporter();
Police police = new Police();
Security security = new Security();
Thief thief = new Thief();
transporter.addWatcher(police);
transporter.addWatcher(security);
transporter.addWatcher(security);
transporter.notifyWatchers();
}
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/121322.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...