设计模式18 - Observer 观察者模式


1. Observer Pattern

1.1. Definition

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

The object which is being watched is called the subject.The objects which are watching the state changes are called observer. Alternatively observer are also called listener.

1.2. Example

The observer pattern is very common in Java. For example you would define a listener for a button in a user interface. If the button is selected the listener is notified and perform a certain action. Similar to text field could add a listener for keyevents.

But the observer pattern is not limited to single user interface components. For example you could have a part A in your application which displays the current temperature.

Another part B displays a green light is the temperature is above 20 degree celsius. To react to changes in the temperature part B registers itself as a listener to Part A.

If the temperature in part A is changed, an event is triggered. This event is send to all registered listeners, as for example part B. Part B receives the changed data and can adjust his display.

1.3. Code example

In the following example the observer is watching changes in a List of People objects.


import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;

public class MyModel {
	private List<Person> persons = new ArrayList<Person>();
	private PropertyChangeListener listener;

	public class Person{
		private String firstName;
		private String lastName;

		public Person(String firstName, String lastName) {
			this.firstName = firstName;
			this.lastName = lastName;
		}
		public String getFirstName() {
			return firstName;
		}
		public void setFirstName(String firstName) {
			notifyListeners(this, "firstName", this.firstName, this.firstName = firstName);
		}
		public String getLastName() {
			return lastName;
		}
		public void setLastName(String lastName) {
			notifyListeners(this, "lastName", this.lastName, this.lastName = lastName);
		}
	}// class Person

	public MyModel() {
		// Just for testing:
		persons.add(new Person("Lars", "Vogel"));
		persons.add(new Person("Jim", "Knopf"));
	}
	public List<Person> getPersons() {
		return persons;
	}
	private void notifyListeners(Object object, String property, String oldValue, String newValue) {
			listener.propertyChange(new PropertyChangeEvent(this, property, oldValue, newValue));
	}
	public void addChangeListener(PropertyChangeListener newListener) {
		listener = newListener;
	}
}


import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

public class MyObserver implements PropertyChangeListener {
	public MyObserver(MyModel model) {
		model.addChangeListener(this);
	}
	public void propertyChange(PropertyChangeEvent event) {
		System.out.println("Changed property: " + event.getPropertyName()
				+ " old: " + event.getOldValue()
				+ " new: " + event.getNewValue());
	}
}


public class Main {
	public static void main(String[] args) {
		MyModel model = new MyModel();
		MyObserver observer = new MyObserver(model);
		// We change the last name of the person, observer will get notified
		for (MyModel.Person person : model.getPersons()) {
			person.setLastName(person.getLastName() + "1");
		}
		// We change the first name of the person, observer will get notified
		for (MyModel.Person person : model.getPersons()) {
			person.setFirstName(person.getFirstName() + "0");
		}
	}
}







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值