首页 > 代码库 > 设计模式11---观察者模式

设计模式11---观察者模式

观察者模式实质就是提取:提取监听对象的过程是相同的,也就是说observer类为根据不同的subject的状态做出相应的反应。

package com.jayfulmath.designpattern.observer;public abstract class Observer {        protected String name;    protected ISubject sub;            public Observer(String name, ISubject sub) {        this.name = name;        this.sub = sub;    }    public abstract void Update();}
public interface ISubject {    public void Attach(Observer obs);    public void Detach(Observer obs);    public void Broadcast();    public String getSubjectStatus();    public void setSubjectStatus(String subjectStatus);}

public class NBALooker extends Observer {

    public NBALooker(String name, ISubject sub) {
        super(name, sub);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void Update() {
        System.out.println(sub.getSubjectStatus()+"\t"+name+"\tstop NBA Look");
    }

}

public class NBALooker extends Observer {    public NBALooker(String name, ISubject sub) {        super(name, sub);        // TODO Auto-generated constructor stub    }    @Override    public void Update() {        System.out.println(sub.getSubjectStatus()+"\t"+name+"\tstop NBA Look");    }}
public class StockLooker extends Observer {    public StockLooker(String name, ISubject sub) {        super(name, sub);        // TODO Auto-generated constructor stub    }    @Override    public void Update() {        // TODO Auto-generated method stub        System.out.println(sub.getSubjectStatus()+"\t"+name+"\tstop Stock Look");    }}
import java.util.ArrayList;import java.util.List;public class Boss implements ISubject {        List<Observer> _mObservers = new ArrayList<Observer>();        public String subjectStatus;        public void Attach(Observer obs)    {        _mObservers.add(obs);    }        public void Detach(Observer obs)    {        _mObservers.remove(obs);    }        public void Broadcast()    {        //here may be asynchronous to notify observer        for(Observer observer :_mObservers)        {            observer.Update();        }    }        /**     * @return the subjectStatus     */    public String getSubjectStatus() {        return subjectStatus;    }    /**     * @param subjectStatus the subjectStatus to set     */    public void setSubjectStatus(String subjectStatus) {        this.subjectStatus = subjectStatus;    }}

main:

public class ObserverMain extends BasicExample {    @Override    public void startDemo() {        ISubject huhanshang = new Boss();        Observer maweidong = ObserverFactory.Factory("NBALooker", "maweidong", huhanshang);        Observer zhangdashang = ObserverFactory.Factory("StockLooker", "zhangdashang", huhanshang);                huhanshang.Attach(maweidong);        huhanshang.Attach(zhangdashang);                huhanshang.setSubjectStatus("I am back! Huhan Shang!");        huhanshang.Broadcast();    }}

 

设计模式11---观察者模式