2015年10月16日 星期五

【筆記】使用Java練習觀察者模式(Observer pattern)

Subject.java
package idv.jk.study.designpattern.observer;

import java.util.ArrayList;
import java.util.List;

public abstract class Subject
{
    private String mMessage;
    List mObserverList = new ArrayList();

    public void add(Observer observer)
    {
        mObserverList.add(observer);
    }

    public void remove(Observer observer)
    {
        mObserverList.remove(observer);
    }

    public void broadcast()
    {
        for(Observer o : mObserverList)
        {
            o.update();
        }
    }

    public String getMessage()
    {
        return mMessage;
    }

    public void setMessage(String message)
    {
        this.mMessage = message;
    }
}
Observer.java
package idv.jk.study.designpattern.observer;

public abstract class Observer
{
    protected String mName;
    protected Subject mSubject;

    public abstract void update();
}
Sheep.java
package idv.jk.study.designpattern.observer;

public class Sheep extends Observer
{
    public Sheep(String name, Subject subject)
    {
        this.mName = name;
        this.mSubject = subject;
        subject.add(this);
    }

    @Override
    public void update()
    {
        System.out.printf("通知 %s:%s%n", mName, mSubject.getMessage());
    }
}
SheepDog.java
package idv.jk.study.designpattern.observer;

public class SheepDog extends Subject
{
}
Main.java
package idv.jk.study.designpattern.observer;

public class Main
{
    public static void main(String[] args)
    {
        //Shaun the sheep中的那隻牧羊犬
        SheepDog bitzer = new SheepDog();

        //chief actor
        Sheep shaun = new Sheep("Shaun", bitzer);

        //Shaun's cousin, is the flock's only lamb,
        Sheep timmy = new Sheep("Timmy", bitzer);

        //Shirley is the largest member of the flock
        Sheep shirley = new Sheep("Shirley", bitzer);

        //Nuts, is quite an eccentric, but useful sheep and usually like the rest of the flock, accompanies and helps Shaun.
        Sheep nuts = new Sheep("Nuts", bitzer);

        bitzer.setMessage("主人回來了,快點恢復正常羊的樣子");
        bitzer.broadcast();

        System.out.println("晚上了...");
        //晚上了,Timmy比較早睡,Bitzer就不通知他
        bitzer.remove(timmy);
        bitzer.setMessage("星星出來了,大家快來看啊");
        bitzer.broadcast();
    }
}

沒有留言: