观察者模式一般是用于消息的推广发送。直白一点,就是一个发消息的,一群接收消息的。
发消息的我们定为Role,接收消息的我们定为People。为了更好的扩展,我们定义一个接口角色Roles,用于管理接受消息的人和发消息,Role实现这个接口
interface Roles{
void addPeople(People people);
void removePeople(People people);
void tellPeople(List<People> peopleList);
}
一个发消息的机构继承Roles
class Role implements Roles{
List<People> peopleList = new ArrayList<>();
public String msg;
public void setMsg(String msg){
this.msg = msg;
tellPeople(peopleList);
}
@Override
public void addPeople(People people) {
peopleList.add(people);
}
@Override
public void removePeople(People people) {
int index = peopleList.indexOf(people);
if(index>0)
peopleList.remove(index);
}
@Override
public void tellPeople(List<People> peopleList) {
for (People peo:peopleList) {
peo.listen(msg);
}
}
}
这里实现了添加接收消息的人,删除接收消息的人,发送消息给所有人(tellPeople);
一个机构发消息,一定要传递消息或者其他信息到接收消息的人那里。而这个消息就是msg,这里暂定为String格式。
一个机构一般会有一个让接收消息的人实现的接口,也就是“听到”消息。
interface Listen{
void listen(String msg);
}
想要收到这个消息,就要实现这个方法,如果用户为People:
class People implements Listen{
public String msg;
public People(Roles role){
role.addPeople(this);
}
@Override
public void listen(String msg) {
System.out.println("消息消费了:"+msg);
}
}
接收消息的人肯定要有一个消息的格式Sring msg ;然后把自己加到发消息的机构Role中的List中,这样就可以接受到消息了。
其实,Roles中的list最好也修改为List<Listen>,这样更容易扩展下。下面是修改后的代码:
public class TellModel {
public static void main(String[] args) {
Role role = new Role();
People people = new People(role);
role.setMsg("消息消费了哦!");
}
interface Roles{
void addPeople(People people);
void removePeople(People people);
void tellPeople(List<Listen> listenList);
}
static class Role implements Roles{
List<Listen> ltList = new ArrayList<>();
public String msg;
public void setMsg(String msg){
this.msg = msg;
tellPeople(ltList);
}
@Override
public void addPeople(People people) {
ltList.add(people);
}
@Override
public void removePeople(People people) {
int index = ltList.indexOf(people);
if(index>0)
ltList.remove(index);
}
@Override
public void tellPeople(List<Listen> listenList) {
for (Listen lis:ltList) {
lis.listen(msg);
}
}
}
interface Listen{
void listen(String msg);
}
static class People implements Listen{
public String msg;
public People(Roles roles){
roles.addPeople(this);
}
@Override
public void listen(String msg) {
System.out.println("消息消费了:"+msg);
}
}
}
如果感觉有点晕,就把接口全部去掉直接一对一,一个机构发给一群特定的人,稍稍修改一下,更容易接受哦~