zoukankan      html  css  js  c++  java
  • PHP多例模式

    学习java就知道设计模式中有多例模式:

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

    大家都知道PHP单例模式,却很少说PHP多例模式,下面是在wikipedia上看到的PHP多例模式的例子:

    <?php
    abstract class Multiton {
        /** by http://www.phpddt.com */
        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\n";
        }
    }
     
    class GoodBye extends Multiton {
        public function __construct($string = 'my', $string2 = 'darling') {
            echo "Goodbye $string $string2\n";
        }
    }
     
    $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 
    ?>
    个人独立博客:www.phpddt.com,关注web开发,欢迎交流!
  • 相关阅读:
    权限设计 【数据库和代码】 GO
    sql读取指定字符前的字符 GO
    C#编码建议 GO
    网页鼠标提示 GO
    ASP.NET设置ie打印两法 GO
    正则表达式入门教程 GO
    一个初学者对ArrayAdapter的简单理解
    泛型的简单理解
    SQL Server死锁详解
    .NET代理模式
  • 原文地址:https://www.cnblogs.com/phpddt/p/3141661.html
Copyright © 2011-2022 走看看