单例(Singleton)模式和不常见的多例(Multiton)模式控制着应用程序中类的数量。如模式名称,单例只能实例化一次,只有一个对象,多例模式可以多次实例化。
基于Singleton的特性,我们经常用Singleton配置应用程序并定义应用程序中可能随时访问的变量。但有时并不推荐使用Singleton,因为它生成了一个全局状态且
该单一根对象没有封装任何系统功能。多数情况下,会使单元测试和调试变得困难。读者根据情况自行决定。
代码示例:
<?<span php </span><span class</span><span SingletonExample{ </span><span private</span> <span function</span> __construct(){}<span //</span><span 防止直接实例化</span> <span public</span> <span static</span> <span function</span> getInstance(){ <span //</span><span 不与任何对象有关联</span> <span static</span> <span $instance</span>=<span null</span>; <span //</span><span 调用此函数的所有代码共享该变量,不必要让其是类的静态变量</span> <span if</span>(<span $instance</span>==<span null</span><span ){ </span><span $instance</span>=<span new</span><span SingletonExample(); } </span><span return</span> <span $instance</span><span ; } } </span><span $obj1</span>=SingletonExample::<span getInstance(); </span><span $obj2</span>=SingletonExample::<span getInstance(); </span><span var_dump</span>(<span $obj1</span>===<span $obj2</span>);<span //</span><span true 是同一个实例</span> ?>
Multiton与singleton相似,不同的是后者需要getInstance()函数传递关键值。
对于给定的关键值只会存在唯一的对象实例,如果有多个节点,每个节点拥有唯一的表识符,且各个节点在某单次执行(如cms里的节点)可能出现多次,那么就可以用Multiton模式实现这些节点啊,Multiton节省内存,并确保同一个对象的多个实例不发生冲突.
示例:
<span 1</span> <?<span php </span><span 2</span> <span class</span><span MultitonExample{ </span><span 3</span> <span private</span> <span function</span> __construct(){}<span //</span><span 防止直接实例化</span> <span 4</span> <span 5</span> <span public</span> <span static</span> <span function</span> getInstance(<span $key</span><span ){ </span><span 6</span> <span static</span> <span $instance</span>=<span array</span><span (); </span><span 7</span> <span if</span>(!<span array_key_exists</span>(<span $key</span>,<span $instance</span><span )){ </span><span 8</span> <span $instance</span>[<span $key</span>]=<span new</span><span SingletonExample(); </span><span 9</span> <span } </span><span 10</span> <span return</span> <span $instance</span>(<span $key</span><span ); </span><span 11</span> <span } </span><span 12</span> <span 13</span> <span }; </span><span 14</span> ?>
参考资料:php和mysql专家编程