观察者模式

当股票的价格上涨或下降5%时,会通知持有该股票的股民,当股民听到价格上涨的消息时会买股票,当价格下降时会大哭一场。

 

抽象目标类:

package com;

public class ConcreteSubject extends Subject{
    @Override
    public void attach(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void detach(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void down() {
        for (Object obs:observers){
            ((Observer)obs).cry();
        }
    }

    @Override
    public void up() {
        for (Object obj:observers){
            ((Observer)obj).buy();
        }
    }

}

  具体目标类

package com;

import java.util.ArrayList;

public abstract class Subject {
    protected ArrayList observers= new ArrayList();
    public abstract void attach(Observer observer);
    public abstract void detach(Observer observer);
    public abstract void down();
    public abstract void up();
}

 

 抽象观察者类:

package com;

public interface Observer {
    void buy();
            void cry();
}

  

具体观察这类: 

 

package com;

public class humin implements Observer{

    @Override
    public void buy() {
        System.out.println("股票上涨,购入");
    }

    @Override
    public void cry() {
        System.out.println("股票下跌,哭");
    }
}

  客户端

package com;

public class Client {
    public static void main(String[] args) {
        Observer gumin1,gumin2,gumin3;
        gumin1=new humin();
        gumin2=new humin();
        gumin3=new humin();

        Subject gupiao =new ConcreteSubject();
        gupiao.attach(gumin1);
        gupiao.attach(gumin2);
        gupiao.attach(gumin3);
        gupiao.up();
        gupiao.down();
    }
}

  

 

posted @ 2021-11-16 11:06  小跳不磕脑袋  阅读(69)  评论(0编辑  收藏  举报