PHP设计模式

本文按如下顺序编写:①注册模式 ②适配器模式 ③观察者模式 ④原型模式

1、注册模式。为实现对象全局共享,将对象保存到数组,这就是注册到注册树。需要时从注册树取出来

class Register{
      protected static $objects;
      public function set($alias,$object){
             self::objects[$alias] = $object; //将对象注册到树上
      }
      public function get($name){
             return self::objects[$name];    //从注册树上取出对象
      }
    public function __unset($alias){
        unset(self::$object[$alias]); //移除对象树上的某个对象
    } }

2、适配器模式。新的接口要实现,旧的接口不能动,这种情况下引入一个新类即适配器,对接新的接口,实现高内聚低耦合。

interface Target{
public function method1();
public function method2();
}

//原来的接口
class Old{
public function method1(){
echo 'this is old method1'.'<br>';
}
}

//适配器。对接原来的接口,实现新的接口method2
class Adater implements Target{
private $adapter;
public function __construct(Old $old){
$this->adapter = $old;
}
public function method1(){
$this->adapter->method1();
}
public function method2()
{
echo 'this is new method2';
}
}
$old = new Old();
$adapter = new Adater($old);
$adapter->method1();
$adapter->method2();

输出结果:
this is old method1
this is new method2


 

3、观察者模式。观察者向主题注册,主题再通知观察者操作。

//主题接口
interface Subject{ public function register(Observer $observer); public function notify(); } //观察者接口 interface Observer{ public function watch(); } //主题实现 class Action implements Subject{ public $_observer = Array(); public function register(Observer $observer){ //将观察者添加到注册树 $this->_observer[] = $observer; } public function notify(){ foreach ($this->_observer as $observer) { //遍历观察者通知 $observer->watch(); } } }
//观察者实现 class Cat implements Observer{ public function watch(){ echo 'here is a cat'.'<br>'; } } class Dog implements Observer{ public function watch(){ echo 'here is a dog'.'<br>'; } } $action = new Action(); $action->register(new Cat); $action->register(new Dog); $action->notify();

输出:
here is a cat
here is a dog

明天要加个小鸡腿,这么晚了还学习了!

4、原型模式。与工厂模式类似,都是用来创建对象的。但是原型模式是用的克隆生成大对象,减少创建时的初始化等操作占用开销

interface Prototype{   
  function copy();  
}

class Student implements Prototype{
  public $name;
  public function __construct($name){
    $this->name = $name
   }
  public function copy(){
    return clone $this;
  }
  public function printInfo(){
    echo $this->name.'<br>';
  }
}

$stu1 = new Student('张三');
$stu1->printInfo();
$stu2 = $stu1->copy();
$stu2->name = '李四';
$stu2->printInfo();
输出结果:
      张三
      李四
原文地址:https://www.cnblogs.com/lisongwei/p/10977203.html