|
學(xué)習(xí)Java就知道設(shè)計(jì)模式中有多例模式:
1、多例類可以有多個(gè)實(shí)例
2、多例類必須能夠自我創(chuàng)建并管理自己的實(shí)例,并向外界提供自己的實(shí)例。
大家都知道php單例模式,卻很少說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ā)生沖突。
php技術(shù):PHP多例模式介紹,轉(zhuǎn)載需保留來(lái)源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。