Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- channel
- http
- package
- C
- write
- FOR
- Golang
- go언어
- 책
- API
- range
- windows
- 영화
- Python
- tcp
- Sync
- mutex
- File
- install
- bitcoin
- window
- go
- Linux
- Close
- GO 언어
- c++
- JavaScript
- json
- 리뷰
- Callback
Archives
- Today
- Total
Code Habit
Singleton pattern 본문
싱글턴 패턴은 소프트웨어 디자인 패턴 중 하나로 프로그램 내에 인스턴스가 오직 하나만 존재하도록 보장하는 패턴이다. 이 패턴은 전역 변수를 사용하지 않고 객체의 단일 인스턴스에 대한 전역적인 접근을 제공한다.
- example
#ifndef _SINGLE_TON_TMPL_
#define _SINGLE_TON_TMPL_
#include <cstddef>
template <typename T>
class Singleton_tmpl : public T
{
public:
Singleton_tmpl() {}
~Singleton_tmpl() {}
static Singleton_tmpl *GetInstance()
{
if (Singleton_tmpl::m_pInstance == nullptr)
{
Singleton_tmpl::m_pInstance = new Singleton_tmpl;
}
m_nRefs++;
return m_pInstance;
}
void Release()
{
if (m_nRefs > 0)
{
m_nRefs--;
if ((m_nRefs == 0) && (m_pInstance))
{
delete m_pInstance;
m_pInstance = nullptr;
}
}
}
private:
static int m_nRefs;
static Singleton_tmpl *m_pInstance;
};
// init staic variables
template <typename T> Singleton_tmpl<T> *Singleton_tmpl<T>::m_pInstance = NULL;
template <typename T> int Singleton_tmpl<T>::m_nRefs = 0;
#endif
특정 클래스 T를 상속받는 클래스를 정의하였다. 클래스 내 정적멤버 변수 m_pInstance, m_nRefs를 선언하여 싱글톤 인스턴스를 관리하며 클래스 외부에서 정적 멤버 변수들을 초기화 하고 있다.
사용 예제이다.
Singleton_tmpl<CDerivedClass> *pDrCls;
pDrcls = Singleton_tmpl::GetInstance();
pDrcls->Functions();
if(pDrCls)
{
pDrCls->Release();
pDrcls = nullptr;
}
T타입으로 CDerivedClass를 사용하는 객체 변수를 선언하여 Getinstance()로 인스턴스를 할당 받는다. 처음 할당 받으면 인스턴스 생성과 동시에 m_nRefs값이 1이 되며 생성된 인스턴스가 반환될 것이고 이미 생성되어 있다면 m_nRefs 값이 1 증가하며 미리 생선된 인스턴스가 반환될 것이다.
사용이 완료된 pDrCls는 Release()를 호출하여 인스턴스 카운팅(m_nRefs)을 하나 줄이거나 인스턴스를(m_pInstance)를 해제 시킨다.