C ++ Factory of templated sigleton

时间:2015-07-03 12:57:10

标签: c++ templates design-patterns singleton factory-pattern

这是一个简单的C ++项目,有2个设计模式:singleton和factory,sigleton也是模板化的类,接口(IHash)和类(Hash1)。 一个简单的工厂类(HashFactory)创建一个sigleton(Hash1); Hash1继承了IHash接口,理想情况下我是Hash1,Hash2 .. HashN。

在编译时我发现错误,问题是什么?

g++  main.cpp 
main.cpp: In static member function ‘static IHash* HashFactory::get(int)’:
main.cpp:11:15: error: ‘static T& Singleton<T>::getInstance() [with T = Hash1]’ is inaccessible
static T &getInstance() {
           ^
main.cpp:76:50: error: within this context
     if (type == 1)return &Hash1::getInstance();
                                              ^

剪切并粘贴此代码以进行编译:

#include <iostream>
using namespace std;
///////////////////////////////////////////////
//Class Singleton
 template<class T>
class Singleton {
public:

static T &getInstance() {
    if (!_instanceSingleton) {
        _instanceSingleton = new T();
    }
    return *_instanceSingleton;
}

private:
    static T *_instanceSingleton;
};

template<class T> T *Singleton<T>::_instanceSingleton = 0;

/////////////////////////////////////////////////
//Interface IHash
class IHash {

public:

    void function1() {
        cout << "function1";
    }

    virtual void recordHash(bool b) = 0;

    ~IHash() {
        dispose();
    }


private:

    void dispose() {
        cout << "dispose\n";
    }
};

///////////////////////////////////////////////////
//Class Hash1 is a singleton and inherits IHash

class Hash1 : public IHash, Singleton<Hash1> {
    friend class Singleton<Hash1>;
public:
    void recordHash(bool b);
private:
    //private constructor, is a sigleton
    Hash1();
};

Hash1::Hash1() {
    cout << "create Hash1\n";
}

void Hash1::recordHash(bool b) {
    cout << b << " recordHash\n";
}


////////////////////////////////////////////////////
//Factory for IHash
class HashFactory {
public:
    static IHash *get(int type) {
        if (type == 1)return &Hash1::getInstance();
//        if (type == 2)return &Hash2::getInstance();
//        if (type == 3)return &Hash3::getInstance();
        return 0;
    }
};

//////////////////////////////////////////////////////

int main() {
    int type=1;
    IHash *a = HashFactory::get(type);
    a->recordHash(true);
    a->function1();
    return 0;
}

1 个答案:

答案 0 :(得分:3)

Hash1Singleton<Hash1>继承的内容是隐式隐私的。将其更改为

class Hash1 : public IHash, public Singleton<Hash1> {