2015-07-03 65 views
0

這裏是一個簡單的項目,在C++中有2個設計模式:singleton和factory,sigleton也是一個模板類,一個接口(IHash)和一個類(Hash1)。 一個簡單的工廠類(HashFactory)創建一個sigleton(Hash1); Hash1繼承了接口IHash,理想情況下我有Hash1,Hash2 .. HashN。模板sigleton的C++工廠

在編譯時我錯了,有什麼問題?

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

你有沒有想過不使用單身設計模式?你也可以在你的課堂上使用靜態的。你確定你需要它嗎? – eroween

+0

@ LouisMartin-Pierrat:或者只是創建一個實例。 'Hash1 my_instance;'。 –

回答

3

Hash1的從Singleton<Hash1>繼承是隱式私有。更改爲

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