php设计模式之单例模式代码

yipeiwu_com5年前PHP代码库

php设计模式之单例模式的例子,供大家参考,具体内容如下

<?php
  /**
   * php设计模式 单例模式
   */
  class Fruit{
    private static $instanceMap = array();

    //protected getter for singleton instances
    protected static function getSingleton($className){
      //保证单例模式 并且不能从控制器实例化和克隆
      if (!isset(self::$instanceMap[$className])) {
        $object = new $className;
        //Make sure this object inherit from Singleton
        if ($object instanceof Fruit) {
          self::$instanceMap[$className] = $object;
          var_dump($object);
        } else {
          throw SingletonException("Class '$className' do not inherit from Singleton!");
        }
      }
      return self::$instanceMap[$className];
    }

    //protected constructor to prevent outside instantiation
    protected function __construct(){}

    //denie cloning of singleton objects
    public final function __clone(){
      trigger_error('It is impossible to clone singleton', E_USER_ERROR);
    }
  }

  class Apple extends Fruit{
    protected $rndId;

    public function __construct(){
      $this->rndId = rand();
    }

    public function whatAmI(){
      echo 'I am a Apple(' . $this->rndId . ')<br />';
    }

    public static function getInstance(){
      //echo get_class();
      return Fruit::getSingleton(get_class());
    }
  }

  class GreenApple extends Apple{
    public function whatAmI(){
      echo 'I am a GreenApple(' . $this->rndId . ')<br />';
    }

    public static function getInstance(){
      return Fruit::getSingleton(get_class());
    }
  }

  $apple1 = Apple::getInstance();
  //var_dump($apple1);
  $apple2 = GreenApple::getInstance();
  $apple1->whatAmI();// should echo 'I am a Apple(some number)
  $apple2->whatAmI();// should echo 'I am a GreenApple(some number)
  $apple1 = Apple::getInstance();
  $apple2 = GreenApple::getInstance();
  //保证单例模式
  $apple1->whatAmI();// should echo 'I am a Apple(same number as above)
  $apple2->whatAmI();// should echo 'I am a GreenApple(same number as above)
  // $a = clone $apple1;// this should fail
  // $b = clone $apple2;// this should fail

以上就是本文的全部内容,希望对大家学习php程序设计有所帮助。

相关文章

PHP正则匹配到2个字符串之间的内容方法

如下所示: $preg= '/xue[\s\S]*?om/i'; preg_match_all($preg,"学并思网址xuebingsi.com",$res); var...

浅析PHP中的字符串编码转换(自动识别原编码)

复制代码 代码如下:/** * 对数据进行编码转换 * @param array/string $data     ...

PHP在字符串中查找指定字符串并删除的代码

$a = "abcababa"; $count=strpos($a,"ab"); $str=substr_replace($a,"",$count,2); 输出结果:cababa 代码虽...

php中判断数组相等的方法以及数组运算符介绍

php中判断数组相等的方法以及数组运算符介绍

如何判断两个数组相等呢?其实很简单,用 == 或者 === 就可以了 php手册里说明如下: 那像 array('k'=>array())这样的多维数组能用如上方法判断相等吗?当...

如何使用php等比例缩放图片

本文介绍了PHP实现图片压缩方法,读者可以根据具体应用参考或加以改进,直接上代码,imgzip($src,$newwid,$newhei)这个函数带进去的分别是原图片、缩放要求的宽度、缩...