观察者模式

观察者:

package ObserverPattern.observer;

import java.util.Observable;
import java.util.Observer;

import ObserverPattern.observerable.Staff;

public class Manager implements Observer{

	@Override
	public void update(Observable observable, Object msg) {
		System.out.println("经理观察到如下情况:");
		Staff staff = (Staff) observable;
		System.out.println(staff.getName()+msg.toString());
	}

}

 

package ObserverPattern.observer;

import java.util.Observable;
import java.util.Observer;

import ObserverPattern.observerable.Staff;

public class Boss implements Observer{

	@Override
	public void update(Observable observable, Object msg) {
		System.out.println("老板观察到如下情况:");
		Staff staff = (Staff) observable;
		System.out.println(staff.getName()+msg.toString());
	}

}

 

被观察者

package ObserverPattern.observerable;

import java.util.Observable;

//员工,被观察
public class Staff extends Observable{

	private String name;
	
	public Staff(String name){
		this.name = name;
	}
	
	public void havaLuanch(){
		setChanged();
		notifyObservers("开始吃饭");
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	
}

 

客户端

package ObserverPattern;

import ObserverPattern.observer.Boss;
import ObserverPattern.observer.Manager;
import ObserverPattern.observerable.Staff;

public class Client {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		Staff staff = new Staff("张三");
		
		Manager manager = new Manager();
		Boss boss = new Boss();
		
		staff.addObserver(manager);
		staff.addObserver(boss);
		
		staff.havaLuanch();
	}

}

  

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