设计模式学习笔记——观察者模式

观察者模式类图(截图来自《大话设计模式》ps:以生活中的故事来分析设计模式,使人不觉得枯燥无味,很赞的一本书!):

设计模式学习笔记——观察者模式

代码结构图:

设计模式学习笔记——观察者模式

Java版代码:

import java.util.ArrayList;



public class Observer {

    public static void main(String[] args) {

        Subject subject = new Secretary();

        AbstractObserver observer1 = new StockObserver("Marry", subject);

        AbstractObserver observer2 = new NBAObserver("Peter", subject);



        subject.attach(observer1);

        subject.attach(observer2);



        subject.setSbjectState("老板回来了");

        subject.inform();

    }



}



abstract class Subject {

    private String sbjectState;

    private ArrayList<AbstractObserver> observers = new ArrayList<>();



    public void attach(AbstractObserver observer) {

        observers.add(observer);

    }



    public void detach(AbstractObserver observer) {

        observers.remove(observer);

    }



    public String getSbjectState() {

        return sbjectState;

    }



    public void setSbjectState(String sbjectState) {

        this.sbjectState = sbjectState;

    }



    public void inform() {

        for (AbstractObserver o : observers) {

            o.update();

        }

    }

}



class Boss extends Subject {

}



class Secretary extends Subject {

}



abstract class AbstractObserver {

    private String name;

    private Subject sub;



    public AbstractObserver(String name, Subject sub) {

        this.setName(name);

        this.setSub(sub);

    }



    public abstract void update();



    public String getName() {

        return name;

    }



    public void setName(String name) {

        this.name = name;

    }



    public Subject getSub() {

        return sub;

    }



    public void setSub(Subject sub) {

        this.sub = sub;

    }

}



class StockObserver extends AbstractObserver {

    public StockObserver(String name, Subject sub) {

        super(name, sub);

    }



    public void update() {

        System.out.println(this.getSub().getSbjectState() + this.getName()

                + "关闭股票行情,继续工作!");

    }

}



class NBAObserver extends AbstractObserver {

    public NBAObserver(String name, Subject sub) {

        super(name, sub);

    }



    @Override

    public void update() {

        System.out.println(this.getSub().getSbjectState() + this.getName()

                + "关闭NBA直播,继续工作!");

    }

}

 

你可能感兴趣的:(观察者模式)