Java 设计模式(12) -- 观察者

Observer

 

Intent
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

How to
Subject
   knows its observers. Any number of Observer objects may observe a subject.
   provides an interface for attaching and detaching Observer objects.
Observer
   defines an updating interface for objects that should be notified of changes in a subject.

Known cases
Listener
MVC
Publish-Subscribe

UML

 Java 设计模式(12) -- 观察者_第1张图片

 

代码样例:

package org.haha.DesignPatterns.observer; import java.util.ArrayList; import java.util.List; public class Observable { private List<Observer> observers; public Observable() { observers = new ArrayList<Observer>(); } public void register(Observer obs) { observers.add(obs); } public void unregister(Observer obs) { observers.remove(obs); } public void remind() { for (Observer obs : observers) { obs.update(this); } } } package org.haha.DesignPatterns.observer; public abstract class Observer { public Observer() { } abstract public void update(Observable subject); } package org.haha.DesignPatterns.observer; import java.util.List; import java.util.ArrayList; public class Subject extends Observable { private List<String> datas = new ArrayList<String>(); public void addData(String data) { datas.add(data); remind(); } public List<String> getDatas() { return datas; } } package org.haha.DesignPatterns.observer; import java.util.List; public class Subscriber extends Observer { private String name; public Subscriber(String name) { super(); this.name = name; } public void update(Observable sub) { if (sub instanceof Subject) { List<String> datas = ((Subject)sub).getDatas(); for (String str : datas) { System.out.println("Name=" +name + " " + str); } } } } package org.haha.DesignPatterns.observer; public class TestObserver { public static void main(String[] args) { Subject subject = new Subject(); Subscriber obs1 = new Subscriber("obs1"); Subscriber obs2 = new Subscriber("obs2"); subject.register(obs1); subject.register(obs2); subject.addData("Test1"); subject.addData("Test2"); } }

你可能感兴趣的:(java,设计模式,String,object,Class,interface)