每天一个设计模式之观察者模式

观察者模式

观察者模式定义了对象之间的一对多依赖关系,这样一来。当一个对象改变状态时,他的所有依赖的对象都会收到通知和更新

简要的来说就是当一个对象改变,在这个对象里面通知其他对象

现在我们用小明的妈妈给她儿子零花钱这个例子来演示这个例子

//主题的抽象接口
public interface Subject{
	public void registerObserver(Oberver o);
	public void removeObserver(Observer o);
	public void notifyObservers();
}

//观察者抽象接口
public interface Oberver{
	public void update(int price);
}

//妈妈主题 妈妈实现抽象接口
public class MomSuject implements Subject{
	private ArrayList obervers;

	public MomSuject(){
		obervers = new ArrayList();
	}

	public void registerObserver(Oberver o){
		obervers.add(o);
	}

	public void removeObserver(Oberver o){
		obervers.remove(o);
	}
	
	public void notifyObservers(){
		for (int i = 0; i < obervers.size() -1; i++) {
			System.out.println(obervers.get(i));
		}
	}

	public void setPrice(int price){
		for (int i = 0; i < obervers.size() -1; i++) {
			obervers.get(i).setPrice(price)
		}
	}
}  

//儿子抽象观察者实现类, 
public class SonObserver implements Observer{
	private int price;

	private MomSuject monSubject;

	public SonObserver(MomSuject monSubject){
		this.monSubject = monSubject;
		monSubject.registerObserver(this);
	}

	public void display(){
		System.out.println(price)
	}
}

//妈妈给孩子们零花钱,孩子将零花钱打印出来
public class ObserverTest{
	Subject monSubject = new MomSuject();
	Obrver bigSon = new SonObserver(monSubject);
	Oberver twoSon = new SonObserver(monSubject);
	Oberver threaSon = new SonObserver(monSubject);

	monSubject.setPrice(100);
	monSubject.setPrice(300);
	monSubject.setPrice(400);
}

在Java中有很多地方都 会用到观察者模式,例如Swingjianting 中事件监听

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
	
public class SwingObserverExample {
	JFrame frame;
	
	public static void main(String[] args) {
		SwingObserverExample example = new SwingObserverExample();
		example.go();
	}
	
	public void go() {
		frame = new JFrame();

		JButton button = new JButton("Should I do it?");
		button.addActionListener(new AngelListener());
		button.addActionListener(new DevilListener());
		frame.getContentPane().add(BorderLayout.CENTER, button);

		// Set frame properties 
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().add(BorderLayout.CENTER, button);
		frame.setSize(300,300);
		frame.setVisible(true);
	}
	
	class AngelListener implements ActionListener {
		public void actionPerformed(ActionEvent event) {
			System.out.println("Don't do it, you might regret it!");
		}
	}

	class DevilListener implements ActionListener {
		public void actionPerformed(ActionEvent event) {
			System.out.println("Come on, do it!");
		}
	}
}

posted on 2017-09-05 22:44  王守昌  阅读(149)  评论(0编辑  收藏  举报

导航