PHP设计模式之-----观察者模式

<?php
/*
 * 观察者模式
 * 其实观察者模式这是一种较为容易去理解的一种模式吧,它是一种事件系统,意味着这一模式允许某个类观察另一个类的状态,当被观察的类状态发生改变的时候,观察类可以收到通知并且做出相应的动作;观察者模式为您提供了避免组件之间紧密耦合的另一种方法 
 * */

// 部队兵种的接口
interface Arms
{
	public function dispatched();
}

// 部队上的总指挥部的接口
interface Subject
{
	public function register( Arms $arms );
	
	public function notify();
}

/**
 * Class Action
 *
 * @describe 定义一个司令部类 如果收到了侦察兵的消息就歼灭敌军
 *
 * @author   nick
 *
 */
class Action implements Subject
{
	// 打这场战咱们有多少部队都告诉我 让我统计一下
	public $_observers = array(); // hi 哥们 你来统计一下兵种
	
	public function register( Arms $observer )
	{
		$this->_observers[] = $observer;
	}
	
	public function notify()
	{
		foreach ( $this->_observers as $observer ) {
			$observer->dispatched();
		}
	}
}

//核导弹部队
class NuclearMissileForce implements Arms
{
	public function dispatched()
	{
		echo '发射核导弹,正中目标!' . '<hr>';
	}
}

//战斗机部队
class Jagdwaffe implements Arms
{
	public function dispatched()
	{
		echo '空中轰炸机部队已经出动!' . '<hr>';
	}
}

//地面特种兵
class GroundSpecialForces implements Arms
{
	public function dispatched()
	{
		echo '地面特种部队正在歼灭敌军!' . '<hr>';
	}
}

/**
 * Class Sentry
 *
 * @describe 哨兵类 负责通知司令部
 *
 * @author   nick
 *
 */
class Sentry
{
	private $action;
	
	public function __construct()
	{
		$this->action = new Action();
	}
	
	// 统计部队上报司令部
	public function ReportToHeadquarters()
	{
		$this->action->register(new NuclearMissileForce());
		$this->action->register(new Jagdwaffe());
		$this->action->register(new GroundSpecialForces());
	}
	
	// 发现敌军 开始战斗
	public function notifyAction()
	{
		$this->ReportToHeadquarters();
		$this->action->notify();
	}
}

$obj = new Sentry();
$obj->notifyAction();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值