멀티턴 패턴(multiton pattern)은 소프트웨어 공학에서 싱글턴 패턴을 일반화시킨 디자인 패턴이다. 싱글턴이 오직 하나의 클래스 인스턴스의 생성만을 허용하는 반면 멀티턴 패턴은 여러 개의 인스턴스의 통제된 생성을 허용하며 을 사용하여 관리된다.

멀티턴의 UML 다이어그램

대부분의 서적에서 이 패턴은 싱글턴 패턴으로 간주된다. 예를 들어 멀티턴은 객체 지향 프로그래밍 서적 디자인 패턴에서 분명히 언급되지 않는다. 싱글턴 레지스트리(registry of singletons)라는 이름의 더 유연한 접근으로 등장한다.

단점

편집

이 패턴은 싱글턴 패턴과 비슷하게 단위 테스트를 훨씬 더 어렵게 만드는데[1], 이는 애플리케이션에 전역 상태를 도입하기 때문이다.

구현

편집

C#에서의 예는 다음과 같다:

using System.Collections.Generic;

public enum MultitonType {
    ZERO,
    ONE,
    TWO
};

public class Multiton {
    private static readonly Dictionary<MultitonType, Multiton> instances =
        new Dictionary<MultitonType, Multiton>();
    private int number;

    private Multiton(int number) {
        this.number = number;
    }

    public static Multiton GetInstance(MultitonType type) {
        // lazy init (not thread safe as written)
        // Recommend using Double Check Locking if needing thread safety
        if (!instances.ContainsKey(type)) {
            instances.Add(type, new Multiton((int)type));
        }
        return instances[type];
    }

    public override string ToString() {
        return "My number is " + number.ToString();
    }

    // Sample usage
    public static void Main(string[] args) {
        Multiton m0 = Multiton.GetInstance(MultitonType.ZERO);
        Multiton m1 = Multiton.GetInstance(MultitonType.ONE);
        Multiton m2 = Multiton.GetInstance(MultitonType.TWO);
        System.Console.WriteLine(m0);
        System.Console.WriteLine(m1);
        System.Console.WriteLine(m2);
    }
}

각주

편집