
[Design Pattern] 5. Singleton Pattern
싱글톤 패턴. 진–짜 많이 쓰는 패턴인데, 일단 한번 만들어봤다.
- 런타임 중 단 하나의 객체임을 보장한다.
장점 1. static으로 구현되어 있기 때문에 접근하기 편하다.(요건 단점이기도 하잖아.)
장점 2. 하나만 있다는 걸 보장해주므로 포인터를 신경쓰지 않아도 된다.
쓰레딩과 관련하여 이슈가 있는데, 어떤 쓰레드가 언제 접근할지를 모른다는 문제점이 생긴다. 그래서 생성하고 있는 중에 다른 쓰레드가 접근하면 또 다시 생성하여 여러 개의 객체가 생겨날 여지가 있다.
자바 같은 경우에는 자체적으로 동기화를 제공해주는데, 뭐 아무튼 여러가지 해결 방법이 있는데 c++에서 내세울 수 있는 건, 그리고 생각나는 건 이정도.
방법 1. 프로그램 시작 시 만들어둔다.
방법 2. 뮤텍스 잠금을 사용한다.
아무튼 이슈는 이정도.
이제 예제를 보자.
// 싱글톤 클래스
class MessageManager{
public:
static MessageManager* getInstance(){
if(_instance == nullptr){
_instance = new MessageManager();
}
return _instance;
}
// 출력
void print(const std::string &str){
cout<<str<<endl;
}
// 거꾸로 출력
void reverse_print(const std::string &str){
std::stack<char> stack;
std::for_each(str.begin(), str.end(), [&stack](const char &data){
stack.push(data);
});
while(!stack.empty()){
cout<<stack.top();
stack.pop();
}
cout<<endl;
}
private:
static MessageManager* _instance;
};
MessageManager* MessageManager::_instance;
int main()
{
MessageManager::getInstance()->print("hello!!!!");
MessageManager::getInstance()->reverse_print("hello!!!!");
return 0;
}