定义
观察者模式定义了一种一对多的依赖关系,让多个观察者同时监听某一个主题,这个主题在状态发生变化时,会通知所有观察者,使它们能够自动更新自己
主题:被观察者
你不必知道怎么调用我,我会调用你
类图
比如说新闻服务器更新了,其他的新闻客户端(电视,平板,手机等等)也会同步更新,在这种场景下,观察者模式就会大显身手,我们将新闻服务器看成被观察者
各种新闻客户端看成观察者,一旦被观察者有更新了,就会通知所有已注册的观察者更新信息,观察者设计模式将被观察者和观察者解耦,也将观察者之间的耦合度
减少到最少,这样在这个设计模式下,每个类都符合最少知识原则和单一职责原则,也能做到对修改关闭,对扩展开放,如果想在加入一个新的观察者,只需要继承
观察者接口,然后把它注册到被观察者中去就好了
示例:
ObserverInterface:
package com.org.observer;
public interface ObserverInterface
{
public void DoNotify(String notifyMsg);
}
TVClient:
package com.org.observer;
public class TVClient implements ObserverInterface
{
@Override
public void DoNotify(String notifyMsg)
{
System.out.println("TV Say:" + notifyMsg);
}
}
PhoneClient:
package com.org.observer;
public class PhoneClient implements ObserverInterface
{
@Override
public void DoNotify(String notifyMsg)
{
System.out.println("Phone Say:"+notifyMsg);
}
}
PadClient:
package com.org.observer;
public class PadClient implements ObserverInterface
{
@Override
public void DoNotify(String notifyMsg)
{
System.out.println("Pad Say:"+notifyMsg);
}
}
Subject:
package com.org.observer;
import java.util.Vector;
public abstract class Subject
{
public abstract void notifyObserver();
Vector<ObserverInterface> vtrObservers;
public Subject()
{
vtrObservers = new Vector<ObserverInterface>();
}
public boolean addObserver(ObserverInterface observer)
{
return vtrObservers.add(observer);
}
public boolean removeObserver(ObserverInterface observer)
{
return vtrObservers.remove(observer);
}
}
NewsServer:
package com.org.observer;
public class NewsServer extends Subject
{
private String msg = "";
public NewsServer()
{
msg = "init Client!!!!";
}
public void notifyObserver()
{
if (!vtrObservers.isEmpty())
{
for (ObserverInterface inter : vtrObservers)
{
inter.DoNotify(getMsg());
}
}
}
public void updateNews(String newMsg)
{
setMsg(newMsg);
notifyObserver();
}
public String getMsg()
{
return msg;
}
public void setMsg(String msg)
{
this.msg = msg;
}
}
Main:
public static void main(String[] args)
{
System.out.println("start Observer test//");
NewsServer server = new NewsServer();
TVClient tv = new TVClient();
PhoneClient phone = new PhoneClient();
PadClient pad = new PadClient();
server.addObserver(tv);
server.addObserver(phone);
server.addObserver(pad);
server.updateNews("first notify clients");
System.out.println(".........second...........");
server.removeObserver(tv);
server.updateNews("second notify clients");
System.out.println("end Observer test//");
}
如果想新增一个客户端,比如PCClient,只需呀让它继承ObserverInterface , 将PCClient通过Subject的addObserver方法注册到被观察者中去就好了,同样要是想移除它,就调用removeObserver方法,增加和删除观察者不需要修改其他的类,对修改关闭,对扩展开放。