學習Java就知道設計模式中有多例模式:
1、多例類可以有多個實例
2、多例類必須能夠自我創建并管理自己的實例,并向外界提供自己的實例。
大家都知道php單例模式,卻很少說php多例模式,下面是在wikipedia上看到的php多例模式的例子:
復制代碼 代碼如下:
<?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()傳遞關鍵值,對于給定的關鍵值,php多例模式只會存在唯一的對象實例,php多例模式節省內存,確保同一個對象的多個實例不發生沖突。
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。