Skip to content

Commit 9569c1e

Browse files
author
Dominik Liebler
committed
added Multiton
1 parent e730ee6 commit 9569c1e

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed

Multiton/Multiton.php

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
<?php
2+
/**
3+
* Created by JetBrains PhpStorm.
4+
* User: dominik
5+
* Date: 21.08.11
6+
* Time: 15:28
7+
* To change this template use File | Settings | File Templates.
8+
*/
9+
10+
namespace DesignPatterns;
11+
12+
/**
13+
* Multiton pattern
14+
*
15+
* Purpose:
16+
* to have only a list of named instances that are used, like a singleton but with n instances
17+
*
18+
* Examples:
19+
* - 2 DB Connectors, e.g. one for MySQL, the other for SQLite
20+
* - multiple Loggers (one for debug messages, one for errors)
21+
*
22+
*
23+
*/
24+
class Multiton
25+
{
26+
/**
27+
*
28+
* the first instance
29+
*/
30+
const INSTANCE_1 = '1';
31+
32+
/**
33+
*
34+
* the second instance
35+
*/
36+
const INSTANCE_2 = '2';
37+
38+
/**
39+
* holds the named instances
40+
*
41+
* @var array
42+
*/
43+
private static $_instances = array();
44+
45+
/**
46+
* should not be called from outside: private!
47+
*
48+
*/
49+
private function __construct()
50+
{
51+
52+
}
53+
54+
/**
55+
* gets the instance with the given name, e.g. Multiton::INSTANCE_1
56+
*
57+
* @param string $instanceName
58+
* @return Multiton
59+
*/
60+
public static function getInstance($instanceName)
61+
{
62+
if ( ! array_key_exists($instanceName, self::$_instances)) {
63+
self::$_instances[$instanceName] = new self();
64+
}
65+
66+
return self::$_instances[$instanceName];
67+
}
68+
69+
/**
70+
* prevent instance from being cloned
71+
*
72+
* @return void
73+
*/
74+
private function __clone()
75+
{
76+
77+
}
78+
79+
/**
80+
* prevent instance from being unserialized
81+
*
82+
* @return void
83+
*/
84+
private function __wakeup()
85+
{
86+
87+
}
88+
}

0 commit comments

Comments
 (0)