关闭

设计模式之观察者模式

437人阅读 评论(0) 收藏 举报

/**
 * 
 */
package com.handy.ps;

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

/**
 * @author handy
 * 
 */
abstract class Subject {
	List<Observer> listObserver = new ArrayList<Observer>();

	public void addObserver(Observer o) {
		listObserver.add(o);
	}

	public void removeObserver(Observer o) {
		listObserver.remove(o);
	}

	public void notifyObserver() {
		for (Observer o : listObserver) {
			o.update();
		}
	}
}

/**
 * 
 */
package com.handy.ps;

/**
 * @author handy
 *
 */
abstract class Observer {
 public abstract void update();
}

/**
 * 
 */
package com.handy.ps;

/**
 * @author handy
 *
 */
public class ConcreteSubject extends Subject{
 private String subjectState;

/**
 * @return the subjectState
 */
public String getSubjectState() {
	return subjectState;
}

/**
 * @param subjectState the subjectState to set
 */
public void setSubjectState(String subjectState) {
	this.subjectState = subjectState;
}


}

/**
 * 
 */
package com.handy.ps;

/**
 * @author handy
 * 
 */
public class ConcreteObserver extends Observer {
	private String name;// 观察者的名字
	private String observerState;// 观察者的状态
	private ConcreteSubject concreteSubject;// 被观察的对象

	/**
	 * @param name
	 * @param concreteSubject
	 */
	public ConcreteObserver(String name, ConcreteSubject concreteSubject) {
		super();
		this.name = name;
		this.concreteSubject = concreteSubject;
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name
	 *            the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the observerState
	 */
	public String getObserverState() {
		return observerState;
	}

	/**
	 * @param observerState
	 *            the observerState to set
	 */
	public void setObserverState(String observerState) {
		this.observerState = observerState;
	}

	/**
	 * @return the concreteSubject
	 */
	public ConcreteSubject getConcreteSubject() {
		return concreteSubject;
	}

	/**
	 * @param concreteSubject
	 *            the concreteSubject to set
	 */
	public void setConcreteSubject(ConcreteSubject concreteSubject) {
		this.concreteSubject = concreteSubject;
	}

	@Override
	public void update() {
		// TODO Auto-generated method stub
		observerState = concreteSubject.getSubjectState();
		System.out.println("观察者:" + this.getName() + "的状态为:"
				+ this.getObserverState());

	}

}

package com.handy.ps;

public class TestPS {
	public static void main(String[] args) {
		ConcreteSubject s = new ConcreteSubject();
		s.addObserver(new ConcreteObserver("Observer1", s));
		s.addObserver(new ConcreteObserver("Observer2", s));
		s.addObserver(new ConcreteObserver("Observer3", s));
		s.setSubjectState("Runing");
		s.notifyObserver();
		s.setSubjectState("Blocking");
		s.notifyObserver();
	}
}



2
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:18471次
    • 积分:413
    • 等级:
    • 排名:千里之外
    • 原创:24篇
    • 转载:0篇
    • 译文:0篇
    • 评论:2条
    最新评论