项长老

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Observer Pattern:

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Frequency of use: high

Participants:
1.Subject
2.Observer
3.ConcreteSubject
4.ConcreteObserver

 

(1)Subject

import java.util.*;
public abstract class Subject
{
	protected ArrayList observers = new ArrayList();
	public abstract void attach(Observer observer);
	public abstract void detach(Observer observer);
	public abstract void notify();
} 

(2)Observer

public interface Observer
{
	public void update();
} 

(3)ConcreteSubject

public class ConcreteSubject extends Subject
{
	public void attach(Observer observer)
	{
		observers.add(observer);
	}
	
	public void detach(Observer observer)
	{
		observers.remove(observer);
	}
	
	public void notify()
	{
		for(Object obs:observers)
		{
			((Observer)obs).update();
		}
	}	
} 

 

(4)ConcreteObserver

public class ConcreteObserver implements Observer
{
	public void update()
	{
		//具体更新代码
	}
} 

(5)Test

Subject subject = new ConcreteSubject();
Observer observer = new ConcreteObserver();
subject.attach(observer);
subject.notify(); 

  

  

posted on 2016-01-24 23:14  项长老  阅读(403)  评论(0编辑  收藏  举报