forked from lcp0578/design-patterns-in-php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Multiton.php
72 lines (63 loc) · 1.68 KB
/
Multiton.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php
/**
* Multiton,Abstract Factory Class
*/
error_reporting(~E_NOTICE);
abstract class FactoryAbstract
{
protected static $instances = array();
public static function getInstance(){
$className = static::getClassName();
if(!(self::$instances[$className] instanceof $className)){
self::$instances[$className] = new $className();
}
return self::$instances[$className];
}
public static function removeInstance(){
$className = static::getClassName();
if(array_key_exists($className, self::$instances)){
unset(self::$instances[$className]);
}
}
public static function getInstanceList(){
return self::$instances;
}
final protected static function getClassName(){
return get_called_class();
}
protected function __construct(){}
final protected function __clone(){}
}
/**
* Factory Class
*/
abstract class Factory extends FactoryAbstract
{
final public static function getInstance(){
return parent::getInstance();
}
final public static function removeInstance(){
parent::removeInstance();
}
}
//using
class FirstProduct extends Factory
{
public $keys = [];
}
class SecondProduct extends FirstProduct
{
}
FirstProduct::getInstance() ->keys[] = 1;
SecondProduct::getInstance()->keys[] = 2;
FirstProduct::getInstance() ->keys[] = 3;
SecondProduct::getInstance()->keys[] = 4;
FirstProduct::getInstance() ->keys[] = 5;
var_dump(FirstProduct::getInstance()->keys);
var_dump(SecondProduct::getInstance()->keys);
var_dump(FactoryAbstract::getInstanceList());
FirstProduct::removeInstance();
var_dump(FactoryAbstract::getInstanceList());
var_dump(FirstProduct::getInstance()->keys);
var_dump(SecondProduct::getInstance()->keys);
var_dump(FactoryAbstract::getInstanceList());