๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๋””์ž์ธํŒจํ„ด

์ถ”์ƒ ์‹ฑ๊ธ€ํ†ค ํŒจํ„ด(Abstract Singleton)

by ์„œ์•„๋ž‘๐Ÿ˜ 2023. 3. 20.

์ถ”์ƒ ์‹ฑ๊ธ€ํ†ค ํŒจํ„ด์€ ์ถ”์ƒํ™” ๋˜์–ด ์žˆ๋Š” ์‹ฑ๊ธ€ํ†ค ํŒจํ„ด์„ ์ƒ์†๋ฐ›์•„์„œ, ์‚ฌ์šฉํ•˜๋Š” ํŒจํ„ด์ž…๋‹ˆ๋‹ค. ๋งŒ์•ฝ ์‹ฑ๊ธ€ํ†ค์œผ๋กœ ๋ณ€๊ฒฝํ•ด์•ผ ํ•˜๋Š” ํด๋ž˜์Šค๊ฐ€ 5๊ฐœ๋ผ๋ฉด, 5๊ฐœ ๋ชจ๋‘ ์‹ฑ๊ธ€ํ†ค ํŒจํ„ด์„ ์ ์šฉํ•˜๊ธฐ ๋ณด๋‹จ ์ƒ์†๊ณผ ํ…œํ”Œ๋ฆฟ์„ ์ด์šฉํ•ด์„œ ์ถ”์ƒํ™”๋œ ์‹ฑ๊ธ€ํ†ค์„ ๊ตฌํ˜„ํ•ฉ๋‹ˆ๋‹ค.

 

๋งค์šฐ ๊ฐ„๋‹จํ•˜๋‹ˆ๊นŒ ๋”ฐ๋ผํ•ด๋ณด์„ธ์š” :)



1. ์ƒ์† ๋ฐ›์„ ์ถ”์ƒํ™” ํด๋ž˜์Šค๋ฅผ ํ…œํ”Œ๋ฆฟ์œผ๋กœ ๊ตฌํ˜„.

<template typename T>
class SingletonTemplate
{
public:
    T* GetInstance()
    {
        if ( m_instance == nullptr ) 
        {
            m_instance = new T();
        }
        
        return m_instance;
    }        

private:
    SingletonTemplate();
    static T* m_instance;
}

Lasy create๋กœ ๊ตฌํ˜„ํ•ด๋ดค์Šต๋‹ˆ๋‹ค. GetInstance๊ฐ€ ์ฒ˜์Œ ํ˜ธ์ถœ๋์„ ๋•Œ ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.

 

 


2. ์‚ฌ์šฉํ•  ํด๋ž˜์Šค์—์„œ ์ถ”์ƒ ์‹ฑ๊ธ€ํ†ค ํด๋ž˜์Šค๋ฅผ ์ƒ์†

class DataHandler : public SingletonTemplate<DataHandler>
{
    ...
}



3. ์ธ์Šคํ„ด์Šค ์‚ฌ์šฉ

const auto* handler = DataHnadler::getInstance();

 

 

๊ฐ„๋‹จํ•˜๊ฒŒ ์ถ”์ƒ ์‹ฑ๊ธ€ํ†ค์„ ๊ตฌํ˜„ํ•œ ์˜ˆ์ œ์ž…๋‹ˆ๋‹ค.

๋Œ“๊ธ€