- 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();
- }
- }