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

 2025-01-16  阅读 497  评论 8  点赞 242

摘要:php设计模式之单例模式的例子,供大家参考,具体内容如下 rndid = rand(); } public function whatami(){ echo 'i am a apple(' . $this->rndid . ')'; } public static function getinstance(){ //echo get_class(); return fruit::getsingleton(get_class()); } } class gr

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程序设计有所帮助。


标签:phpphp教程

评论列表:

  •   xiaoming22
     发布于 2天前回复该评论
  • 写的很不错,学到了!
显示更多评论

发表评论:

管理员

承接各种程序开发,外贸网站代运营,外贸网站建设等项目
  • 内容2460
  • 积分67666
  • 金币86666

Copyright © 2024 LS'Blog-保定PHP程序员老宋个人博客 Inc. 保留所有权利。 Powered by LS'blog 3.0.3

页面耗时0.0277秒, 内存占用1.94 MB, 访问数据库31次

冀ICP备19034377号