当前位置: 移动技术网 > IT编程>开发语言>PHP > PHP多例模式介绍

PHP多例模式介绍

2019年04月08日  | 移动技术网IT编程  | 我要评论
学习java就知道设计模式中有多例模式: 1、多例类可以有多个实例2、多例类必须能够自我创建并管理自己的实例,并向外界提供自己的实例。 大家都知道php单例模式,却很少

学习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多例模式节省内存,确保同一个对象的多个实例不发生冲突。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网