forked from DesignPatternsPHP/DesignPatternsPHP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Multiton.php
87 lines (75 loc) · 1.75 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
namespace DesignPatterns;
/**
* Multiton pattern
*
* --------------------------------------------------------------------------------------------------------------
* THIS IS CONSIDERED TO BE AN ANTI-PATTERN! FOR BETTER TESTABILITY AND MAINTAINABILITY USE DEPENDENCY INJECTION!
* --------------------------------------------------------------------------------------------------------------
*
* Purpose:
* to have only a list of named instances that are used, like a singleton but with n instances
*
* Examples:
* - 2 DB Connectors, e.g. one for MySQL, the other for SQLite
* - multiple Loggers (one for debug messages, one for errors)
*
*
*/
class Multiton
{
/**
*
* the first instance
*/
const INSTANCE_1 = '1';
/**
*
* the second instance
*/
const INSTANCE_2 = '2';
/**
* holds the named instances
*
* @var array
*/
private static $instances = array();
/**
* should not be called from outside: private!
*
*/
private function __construct()
{
}
/**
* gets the instance with the given name, e.g. Multiton::INSTANCE_1
* uses lazy initialization
*
* @param string $instanceName
*
* @return Multiton
*/
public static function getInstance($instanceName)
{
if (!array_key_exists($instanceName, self::$instances)) {
self::$instances[$instanceName] = new self();
}
return self::$instances[$instanceName];
}
/**
* prevent instance from being cloned
*
* @return void
*/
private function __clone()
{
}
/**
* prevent instance from being unserialized
*
* @return void
*/
private function __wakeup()
{
}
}