GGym's Practice Notes

6장. 싱글턴 패턴 본문

Design Pattern/게임 디자인패턴

6장. 싱글턴 패턴

GGym_ 2020. 5. 7. 17:35

한개의 인스턴스만 갖는 싱글턴 패턴을 적용시켜 파일시스템을 구축해보는 예제를 보고 적용해보았다. 예제코드를 제대로 돌아가게 만들기 위해 간단히 손보았다. (private으로 되어있는 생성자 때문에 friend 클래스를 쓴다든지...)

결과적으론 잘 작동한다. 한개의 인스턴스만 생성이 되며 플랫폼에 맞는 자식 클래스가 생성이 된다.

#include<iostream>
using namespace std;

//#define SWITCH
#define PLAYSTATION4

class FileSystem{
public:
    static FileSystem& instance();

    virtual ~FileSystem(){}
    virtual char* readFile(char* path)=0;
    virtual void writeFile(char* path, char* contents)=0;
    virtual void loadFileSystem()=0;

    friend class PS4FileSystem;
    friend class NSFileSystem;
private:
    FileSystem(){}
};

class PS4FileSystem : public FileSystem{
public:
    virtual char* readFile(char* path){
        // 소니의 파일 IO API를 사용한다...
        return path;
    }
    virtual void writeFile(char* path, char* contents){
        // 소니의 파일 IO API를 사용한다...
    }
    virtual void loadFileSystem(){
        cout << "PS4" << endl;
    }
};

class NSFileSystem : public FileSystem{
public:
    virtual char* readFile(char* path){
        // 닌텐도의 파일 IO API를 사용한다...
        return path;
    }
    virtual void writeFile(char* path, char* contents){
        // 닌텐도의 파일 IO API를 사용한다...
    }
    virtual void loadFileSystem(){
        cout << "SWITCH" << endl;
    }
};

FileSystem& FileSystem::instance(){
    #ifdef PLAYSTATION4
        static FileSystem* instance = new PS4FileSystem();
    #elif defined SWITCH
        static FileSystem* instance = new NSFileSystem();
    #endif
    return *instance;
}
int main(){
    FileSystem& fs = FileSystem::instance();

    //FileSystem& fs = new NSFileSystem();  // error!
    //FileSystem fs2; // error!

    fs.loadFileSystem();   
    return 0;
}

'Design Pattern > 게임 디자인패턴' 카테고리의 다른 글

7장. 상태 패턴  (0) 2020.08.16
2장. 명령 패턴  (0) 2020.05.07
5장. 프로토타입 패턴  (0) 2020.04.27
4장. 관찰자 패턴  (0) 2020.04.17
11장. 바이트코드 패턴  (0) 2020.03.25