php5种开发模式(PHP常见的设计模式)
php5种开发模式(PHP常见的设计模式)}}class Pig extends Aniaml{public function say(){echo "pig";
策略模式
<?php
abstract class Aniaml{
abstract public function say();
}
class Pig extends Aniaml{
public function say(){
echo "pig";
}
}
class Bee extends Aniaml{
public function say(){
echo "bee";
}
}
class Say{
public function call($object){
return $object->say();
}
}
$obj=new Say();
$obj->call(new Pig());
工厂模式interface Aniaml{
public function say();
}
class Pig implements Aniaml{
public function say(){
echo "pig";
}
}
class Bee implements Aniaml{
public function say(){
echo "bee";
}
}
//定义工厂类
class Plant{
static function pig(){
return new Pig;
}
static function bee(){
return new Bee;
}
}
$obj=Plant::bee();
$obj->say();
单列模式<?php
class Aniaml{
private $name;
//私有构造方法 类不能被new
private function __construct(){
}
static public $instance; //保存类中唯一单列
static public function getinstance(){
if(!self::$instance) self::$instance=new self(); //判断类是否被实例化
return self::$instance; //返回单列
}
public function say(){
echo "hi";
}
}
$obj = Aniaml::getinstance();
$obj->say();
观察者模式/**
* 事件产生类
* Class EventGenerator
*/
abstract class EventGenerator
{
private $ObServers = [];
//增加观察者
public function add(ObServer $ObServer)
{
$this->ObServers[] = $ObServer;
}
//事件通知
public function notify()
{
foreach ($this->ObServers as $ObServer) {
$ObServer->update();
}
}
}
/**
* 观察者接口类
* Interface ObServer
*/
interface ObServer
{
public function update($event_info = null);
}
/**
* 观察者1
*/
class ObServer1 implements ObServer
{
public function update($event_info = null)
{
echo "观察者1 收到执行通知 执行完毕!\n";
}
}
/**
* 观察者1
*/
class ObServer2 implements ObServer
{
public function update($event_info = null)
{
echo "观察者2 收到执行通知 执行完毕!\n";
}
}
/**
* 事件
* Class Event
*/
class Event extends EventGenerator
{
/**
* 触发事件
*/
public function trigger()
{
//通知观察者
$this->notify();
}
}
//创建一个事件
$event = new Event();
//为事件增加旁观者
$event->add(new ObServer1());
$event->add(new ObServer2());
//执行事件 通知旁观者
$event->trigger();