需求:主体有两种事件,观察者可以任意关注其中的某个事件或全部事件,当主体事件发生,通知对应的观察者。
创新互联专注为客户提供全方位的互联网综合服务,包含不限于网站设计制作、成都做网站、北碚网络推广、小程序定制开发、北碚网络营销、北碚企业策划、北碚品牌公关、搜索引擎seo、人物专访、企业宣传片、企业代运营等,从售前售中售后,我们都将竭诚为您服务,您的肯定,是我们大的嘉奖;创新互联为所有大学生创业者提供北碚建站搭建服务,24小时服务热线:13518219792,官方网址:www.cdcxhl.com例如:主体是商场,有新货上架和降价两种事件,消费者可以关注其中的一种或全部事件,当降价了,可以通知所有关注降价的消费者。
目录:
主体:
import java.util.ArrayList;
import java.util.List;
public abstract class Observable {
private List
private List
public void attachone(Observer observer) {
listone.add(observer);
System.out.println("添加一个上架观察者");
}
public void detachone(Observer observer) {
listone.remove(observer);
}
public void nodifyObserversone(String newState) {
for(Observer observer:listone) {
observer.updateone(newState);
}
}
public void attachtwo(Observer observer) {
listtwo.add(observer);
System.out.println("添加一个降价观察者");
}
public void detachtwo(Observer observer) {
listtwo.remove(observer);
}
public void nodifyObserverstwo(String newState) {
for(Observer observer:listtwo) {
observer.updatetwo(newState);
}
}
}
具体主体:
public class Market extends Observable{
private String putawaystate;
private String depreciatestate;
public String getPutawayState() {
return putawaystate;
}
public String getDepreciateState() {
return depreciatestate;
}
public void changeputawaystate(String newState) {
putawaystate =newState;
System.out.println("发布主题状态:"+putawaystate);
this.nodifyObserversone(putawaystate);
}
public void changedepreciatestate(String newState) {
depreciatestate =newState;
System.out.println("发布主题状态:"+depreciatestate);
this.nodifyObserverstwo(depreciatestate);
}
}
观察者:
public abstract class Observer {
private String name;
public Observer(String name) {
this.name=name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name=name;
}
public abstract void updateone(String state);
public abstract void updatetwo(String state);
}
具体观察者:
public class Consumer extends Observer{
public Consumer(String name) {
super(name);
}
private String putawaystate;
private String depreciatestate;
public void updateone(String state) {
putawaystate =state;
System.out.println(super.getName()+"状态为:"+putawaystate);
}
public void updatetwo(String state) {
depreciatestate =state;
System.out.println(super.getName()+"状态为:"+depreciatestate);
}
}
客户端:
public class Client {
public static void main(String[] args) {
Market market = new Market();
Observer observerthree =new Consumer("1");
market.attachone(observerthree);
market.attachtwo(observerthree);
market.changeputawaystate("商品B上架");
market.changedepreciatestate("商品B降价");
System.out.println("~~~~~~~~~~~");
Observer observerone =new Consumer("2");
market.attachone(observerone);
market.changeputawaystate("商品A上架");
System.out.println("~~~~~~~~~~~");
Observer observertwo =new Consumer("3");
market.attachtwo(observertwo);
market.changedepreciatestate("商品A降价");
System.out.println("~~~~~~~~~~~");
}
}
实验结果:
类图:
你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧