1.4. 멀티턴 (Multiton)¶
안티패턴이 될 수 있기 때문에 사용에 고려해 보아야 합니다! 더 나은 테스트가능성(Testablity)과 유지가능성(Maintainability)을 위해서 의존성 주입(Dependency Injection)을 사용하세요!
1.4.1. 사용 목적¶
사용중인 이름있는 인스턴스만을 리스트로 갖고 싶을 때 사용합니다. 싱글턴과 유사하지만 싱글턴은 1개의 인스턴스를, 멀티턴은 n개의 인스턴스를 갖는 다는 점이 다릅니다.
1.4.2. 예시¶
2개의 데이터베이스 커넥터. 이를테면 하나는 MySQL, 또다른 하나는 SQLite.
여러개의 로거(Logger). (하나는 디버그 메시지용, 또 하나는 에러처리용)
1.4.3. UML 다이어그램¶
1.4.4. 코드¶
코드는 또한 GitHub 에서 볼 수 있습니다.
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 | <?php
namespace DesignPatterns\Creational\Multiton;
/**
* class Multiton
*/
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()
{
}
}
|