设计模式java——观察者模式

观察者模式(Observer):定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态发生变化时,会通知所有观察者对象,使它们能够自动更新自己。

观察者模式Demo:

/**
 * 2018年3月29日下午8:59:35
 */
package com.Designpattern;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xinwenfeng
 *
 */
public class TestObserver {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		MySubject sentinel = new Sentinel();
		sentinel.addObserver(new GunTeam("机枪"));
		sentinel.addObserver(new MineTeam("布雷"));
		sentinel.addObserver(new MortarTeam("迫击炮"));
		sentinel.notifyObserver("小鬼子来啦!");
	}

}
//抽象观察者
interface MyObserver{
	public void doSomething(String message);
}
//抽象主题
interface MySubject{
	public void addObserver(MyObserver o);
	public void removeObserver(MyObserver o);
	public void notifyObserver(String message);
}
class GunTeam implements MyObserver{
	private String name;
	public GunTeam(String name) {
		this.name = name;
	}

	@Override
	public void doSomething(String message) {
		System.out.println("收到 "+message+" 的消息,"+name+"小队开火狠狠打。");
	}
	
}
class MineTeam implements MyObserver{
	private String name;
	public MineTeam(String name) {
		this.name = name;
	}
	@Override
	public void doSomething(String message) {
		System.out.println("收到 "+message+" 的消息,"+name+"小队拉响地雷。");
	}
	
}
class MortarTeam implements MyObserver{
	private String name;
	public MortarTeam(String name) {
		this.name = name;
	}
	@Override
	public void doSomething(String message) {
		System.out.println("收到 "+message+" 的消息,"+name+"小队发射炮弹。");
	}
}
class Sentinel implements MySubject{
	List list = new ArrayList<>();

	@Override
	public void addObserver(MyObserver o) {
		list.add(o);
	}

	@Override
	public void removeObserver(MyObserver o) {
		list.remove(o);
	}

	@Override
	public void notifyObserver(String message) {
		for(MyObserver o:list) {
			o.doSomething(message);
		}
	}
}

结果:


你可能感兴趣的:(设计模式Demo)