zoukankan      html  css  js  c++  java
  • PHP多例模式介绍_PHP教程

    1、多例类可以有多个实例
    2、多例类必须能够自我创建并管理自己的实例,并向外界提供自己的实例。

    大家都知道PHP单例模式,却很少说PHP多例模式,下面是在wikipedia上看到的PHP多例模式的例子:
    abstract class Multiton { 
    private static $instances = array(); 
    public static function getInstance() { 
    $key = get_called_class() . serialize(func_get_args()); 
    if (!isset(self::$instances[$key])) { 
    $rc = new ReflectionClass(get_called_class()); 
    self::$instances[$key] = $rc->newInstanceArgs(func_get_args()); 

    return self::$instances[$key]; 



    class Hello extends Multiton { 
    public function __construct($string = 'World') { 
    echo "Hello $string "; 



    class GoodBye extends Multiton { 
    public function __construct($string = 'my', $string2 = 'darling') { 
    echo "Goodbye $string $string2 "; 



    $a = Hello::getInstance('World'); 
    $b = Hello::getInstance('bob'); 
    // $a !== $b 

    $c = Hello::getInstance('World'); 
    // $a === $c 

    $d = GoodBye::getInstance(); 
    $e = GoodBye::getInstance(); 
    // $d === $e 

    $f = GoodBye::getInstance('your'); 
    // $d !== $f 
    ?>

    可以看到PHP多例模式需要getInstance()传递关键值,对于给定的关键值,PHP多例模式只会存在唯一的对象实例,PHP多例模式节省内存,确保同一个对象的多个实例不发生冲突。

  • 相关阅读:
    php 建立类POST/GET 的HTTP请求
    上传文件
    golang精选100题带答案
    go面试
    golang反射
    go语言中type的几种使用
    写个版本迭代的方法 例如1.0.9 迭代为1.1.0 到10自动往前进1
    压缩文件和解压文件
    go语言中的文件创建,写入,读取,删除
    go面试题
  • 原文地址:https://www.cnblogs.com/qxandxt/p/10362482.html
Copyright © 2011-2022 走看看