Skip to content

Instantly share code, notes, and snippets.

@kciter
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kciter/9387943 to your computer and use it in GitHub Desktop.
Save kciter/9387943 to your computer and use it in GitHub Desktop.
싱글톤 패턴 (Singleton Pattern)

싱글톤 패턴이란 단 하나의 객체로 존재해야하는 객체를 구현해야 할 때 많이 사용된다.
주로 객체의 부적절한 의존관계를 지우기 위해 많이 사용되지만 객체지향 개념을 잘 모르고 사용할 경우 오히려 더 안좋은 코드가 될 가능성이 높다.

소스는 다음과 같다. (C++로 작성됨)

#include <stdio.h>

class MyClass
{
public:
    MyClass* GetInstance()
    {
        if ( pInstance == nullptr )
            pInstance = new MyClass();
        return pInstance;
    }
    void ReleaseInstance()
    {
        if ( pInstance != nullptr )
            delete pInstance;
    }
public:
    void PrintNum(int num)
    {
        printf("%d\n", num);
    }
private:
    MyClass(){}
    ~MyClass(){}
}

int main()
{
    MyClass::GetInstance()->Print(1);
    return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment