import java.util.Vector;
//观察者设计模式
public class ObserverClient
{
public static void main(String[] args)
{
Subject sub=new Event();
sub.attach(new observer1());
sub.attach(new observer2());
sub.doSomething();
}
}
abstract class Subject
{
Vector<Observer> vector=new Vector<Observer>();
public void attach(Observer o)
{
vector.add(o);
}
public void detach(Observer o)
{
vector.remove(o);
}
public void notifyObserver()
{
for(Observer o : vector)
{
o.update();
}
}
public abstract void doSomething();
}
class Event extends Subject
{
public void doSomething()
{
notifyObserver();
}
}
interface Observer
{
public void update();
}
class observer1 implements Observer
{
public void update() {
System.out.println("observer1 be updated");
}
}
class observer2 implements Observer
{
public void update() {
System.out.println("observer2 be updated");
}
}
java笔试题-> 观察者设计模式2
最新推荐文章于 2024-09-05 11:00:53 发布