|
学习java就知道设计模式中有多例模式:
1、多例类可以有多个实例
2、多例类必须能够自我创建并管理自己的实例,并向外界提供自己的实例。
大家都知道PHP单例模式,却很少说PHP多例模式,下面是在wikipedia上看到的PHP多例模式的例子:
[U]复制代码[/U] 代码如下:
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多例模式节省内存,确保同一个对象的多个实例不发生冲突。
您可能感兴趣的文章:php 设计模式之 单例模式php设计模式 Singleton(单例模式)PHP最常用的2种设计模式工厂模式和单例模式介绍php单例模式实现(对象只被创建一次)基于php设计模式中单例模式的应用分析鸡肋的PHP单例模式应用详解php设计模式之单例、多例设计模式的应用分析
|
|