mercredi 14 août 2019

How can I improve my simple factory pattern?

Now I use a singleton factory to create objects. I originally wanted to register with each new class, so I don't need to change the existing factory class, but I am now exposing Class CproductA to the user. How do I design it?

There are three questions as follows. (1)Class CProductA and class CProductB expose to the user. (2)I need to create the object in advance. (3)m_Map needs to be a global variable.

 #include <map>
 #include <iostream>
 using namespace std;

 //Abstract
 class CProduct
 {
  public:
     virtual void Operation() = 0;
 };

 class CProductA
 {
 public:
     virtual void Operation()
     {
        cout << "Operation A" << endl;
     }
 };

 class CProductB
 {
 public:
     virtual void Operation()
     {
        cout << "Operation B" << endl;
     }
 };

 //Simple Factory
 map <int, CProduct*> m_Map;

 class CSimpleFactory
 {
 public:
    void RegisteProduct(int nId, CProduct* pProduct)
    {
       m_Map[nId] = pProduct;
    }
    void CreateProduct(nId)
    {
       m_Map[nId]->Operation();
    }
    static CSimpleFactory* GetInstance()
    {
       if(m_Instance)
       {
           m_Instance = new CSimpleFactory;
       }
       return m_Instance;
    }
    void Release()
    {
       if(m_Instance)
       {
           delete m_Instance;
       }
    }
 private:
    static CSimpleFactory* m_Instance;
 };

    CSimpleFactory* CSimpleFactory::m_Instance = NULL;


 int main()
 {
     CSimpleFactory::GetInstance->RegisteProduct(1,new CProductA);
     CSimpleFactory::GetInstance->RegisteProduct(2,new CProductB);
      CSimpleFactory::GetInstance->CreateProduct(1);
 }

Aucun commentaire:

Enregistrer un commentaire