Work & Programming/System Design

[Creational Pattern] - Singleton

자전거통학 2024. 5. 15. 10:14

https://refactoring.guru/design-patterns/singleton

 

Singleton

Real-World Analogy The government is an excellent example of the Singleton pattern. A country can have only one official government. Regardless of the personal identities of the individuals who form governments, the title, “The Government of X”, is a g

refactoring.guru

 

프로그램 life cycle안에서 유일한 객체 생성을 목표로 할 때 사용. 

 

예 - 각종 manager class. 

 

특징 - 전역변수 처럼 사용하여, Dependency Inversion을 저해하는 경우를 종종 초래하므로, 제한적 사용을 권유.

 

예제 코드 

 

더보기
public class ABManagerSingleton
{
    static ABManagerSingleton instance = null;

    public ABManagerSingleton GetInstance()
    {
        if(instance == null)
            instance = new ABManagerSingleton();
        return instance;
    }

    public void DoSome()
    {

    }
}

public class SingletonDemo
{
    public void Run()
    {
        ABManagerSingleton absMng = new ABManagerSingleton();
        absMng.GetInstance();
    }
}