欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PHP多例模式介紹

 更新時(shí)間:2013年06月24日 23:55:49   作者:  
學(xué)習(xí)java就知道設(shè)計(jì)模式中有多例模式

學(xué)習(xí)java就知道設(shè)計(jì)模式中有多例模式:

1、多例類可以有多個(gè)實(shí)例
2、多例類必須能夠自我創(chuàng)建并管理自己的實(shí)例,并向外界提供自己的實(shí)例。

大家都知道PHP單例模式,卻很少說(shuō)PHP多例模式,下面是在wikipedia上看到的PHP多例模式的例子:

復(fù)制代碼 代碼如下:

<?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\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
?>

可以看到PHP多例模式需要getInstance()傳遞關(guān)鍵值,對(duì)于給定的關(guān)鍵值,PHP多例模式只會(huì)存在唯一的對(duì)象實(shí)例,PHP多例模式節(jié)省內(nèi)存,確保同一個(gè)對(duì)象的多個(gè)實(shí)例不發(fā)生沖突。

相關(guān)文章

最新評(píng)論