观察者模式(observer)

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

观察者模式(observer)_第1张图片

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(); 

  

  

你可能感兴趣的:(观察者模式(observer))