mercredi 20 juillet 2016

Is factory method the only way of incorporating different classes? (c++)

I give the following codes to illustrate my question:

class Basic 
{
  public:
      Basic();
      ~Basic();
};

class ExtendA: public Basic
{
  public:
      class Para
      {
       };
      Para para_;

};
class ExtendB: public Basic
{
   public:
    class Para
    {

     };
    Para para_;
};

enum Method
{
   MedExtendA, 
   MedExtendB,
   MedExtendAVar1,
   MedExtendBVar1
};

class Enginee
{
 public: 
     class Para()
     {
      public:
         ExtendA::Para paraA_;
         ExtendB::Para paraB_;
     };
     Para paraEnginee_;
     Enginee(Method med)
     {
         switch(med):
         {
           case MedExtendA:
              pBasic.reset(new ExtendA());
              break;
           case MedExtendAVar1:
              pBasic.reset(new ExtendA());
              ExtendA *p = dynamic_cast<ExtendA *> (pBasic.get());
              p.para_ = ; // set the parameter
              break;
           case MedExtendB:
                 ...
              break;
           case MedExtendBVar1:
                  ...
              break;

         }
     }
     ~Enginee()
     {
      }
     boost::shared_ptr<Basic> pBasic;
 };

From the above example, we can see that Basic is the base class while ExtendA and ExtendB are derived class based on Basic class. class Enginee is a factory class, which facilitates invoking other classes. The reason why Enginee class is needed can be shown in the following example:

Without Enginee class:

ExtendA objA;
objA.para_ /// parameter setting
objA.do_something(); 

With Enginee class:

   Enginee myEngine(MedExtendAVar1);
     myEngine.do_something();

In a word, using factory method to construct a Enginee class gives a uniform interface for using ExtendA and ExtendB class. In the above example, depending on parameter setting, we can kind of create different varieties of classes, which can be invoked very easily. However, it also makes the codes more complicated. So here is my question: are there other alternative solutions? what's the problem of the proposed solution?

Aucun commentaire:

Enregistrer un commentaire