潮起又潮落

那些年,我们在一起

设计模式之观察者模式

/**
 * 
 */
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();
	}
}



阅读更多
个人分类: 设计模式
上一篇设计模式之单例模式
下一篇Android socket 编程常见问题
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭