观察者模式(Observer)

观察者模式属于行为型模式,所谓观察模式,观察者订阅了某种服务,那么该服务有变化会通知观察者。

简单的类图:


public interface EventObserver {
    public void speek();
}
public interface EventSubject {
    public void registerOberver(EventObserver observer);
    public void removeOberver(EventObserver observer);
    public void notifiedOberver();
}

public class observer1 implements EventObserver{
    @Override
    public void speek() {
        System.out.println("observer1");
    }
}
public class observer2 implements EventObserver{
    @Override
    public void speek() {
        System.out.println("observer2");
    }
}

public class observer3 implements EventObserver{
    @Override
    public void speek() {
        System.out.println("observer3");
    }
}
public class Subject implements EventSubject{
    private List<EventObserver> list = new ArrayList<>();
    private static Subject subject = null;
    private Subject(){

    }
    public static Subject newInstance(){
        if(subject ==null){
            subject = new Subject();
        }
        return subject;
    }
    @Override
    public void registerOberver(EventObserver observer) {
        list.add(observer);
    }
    @Override
    public void removeOberver(EventObserver observer) {
       list.remove(observer);
    }
    @Override
    public void notifiedOberver() {
      for(EventObserver c:list){
          c.speek();
      }
    }
}

public class test {
    public static void main(String[] args){
        observer1 o1 = new observer1();
        observer2 o2 = new observer2();
        observer3 o3 = new observer3();
        Subject subject = Subject.newInstance();
        subject.registerOberver(o1);
        subject.registerOberver(o2);
        subject.registerOberver(o3);
        subject.notifiedOberver();
        System.out.println("======================");
        subject.removeOberver(o1);
        subject.notifiedOberver();
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值