如何在不使用“朋友”但允许继承的情况下允许另一个人创建一个类?

时间:2017-03-29 23:12:10

标签: c++ inheritance components friend

我的游戏引擎总共有三个类,一个是从中继承所有组件的抽象IComponent类,一个组件类(本例中我将使用RenderComponent)和一个ComponentManager。我希望ComponentManager类能够使用RenderComponent的构造函数,但我不希望任何其他类创建RenderComponent的实例,但我不想使用'friend',因为我希望客户用户组件继承来自IComponent并自动在ComponentManager中使用,而不允许实例化它们自己。代码示例模糊地显示了我想要发生的行为:

class GameObject;

class IComponent
{
    private:
        IComponent() { }
        ~IComponent() { }
    public:
        GameObject* Parent;
}

class RenderComponent : IComponent
{
    public:
        RenderComponent() { }
        ~RenderComponent() { }
}

class ComponentManager
{
    public:
        ComponentManager() { }
        ~ComponentManager() { }

        // normally this would be a template function, but for the sake of this example I will directly use RenderComponent
        RenderComponent* CreateComponent()
        {
            // this would not throw a compiler error
            return new RenderComponent();
        }
}

int main()
{
    ComponentManager manager;

    // even though the constructor of RenderComponent is public, this would throw an error
    RenderComponent* render = new RenderComponent();

    // this however would work perfectly fine
    RenderComponent* render = manager.CreateComponent();

}

重申一下,我想要它,以便创建组件的用户工作量最小。另一个选择当然是让两者都是公共构造函数,但是这样做,虽然你可以在任何你想要的地方创建一个组件,但它将毫无用处。

2 个答案:

答案 0 :(得分:1)

如果您使用工厂设计模式,ComponentManager不需要了解IComponent的具体子类型。不需要将其声明为子类型的朋友。它可以简单地使用 factory 来构造对象。

IComponent子类型的创建者需要为要构造的子类型的实例注册一种方式。他们在工厂中注册一个函数或类,可以构造一个类的实例。

示例程序

#include <iostream>
#include <map>
#include <string>

class GameObject;

class IComponent
{
   // Make sure that sub-classes of IComponent can use the constructor
   // and the destructor.
   protected:
      IComponent() { }
      ~IComponent() { }

   public:
      GameObject* Parent;
};

// Define a function type that can construct a Component.
using ComponentConstructor = IComponent*  (*)();

// Define the interface for the factory.
class ComponentFactory
{
   public:

      // A type alias for simpler coding.
      using ConstructorMap = std::map<std::string, ComponentConstructor>;

      // Allow creators of sub-classes of IComponent to register a
      // function that can be used to construct the sub-type.
      static void registerComponentConstructor(std::string const& componentType,
                                               ComponentConstructor constructor);

      // Construct a Component by providing a name corresponding
      // to the derived sub-type of IComponent.
      static IComponent* constructComponent(std::string const& componentType);

   private:

      // Private function that maintains a map of
      // constructors.
      static ConstructorMap& getConstructrMap();
};

// -----------------------------------------------------
// BEGIN implementation of ComponentFactory.
// It can, obviously, be in a .cpp file of its own.
void ComponentFactory::registerComponentConstructor(std::string const& componentType,
                                                    ComponentConstructor constructor)
{
   getConstructrMap()[componentType] = constructor;
}

IComponent* ComponentFactory::constructComponent(std::string const& componentType)
{
   ConstructorMap& constructorMap = getConstructrMap();
   ConstructorMap::iterator iter = constructorMap.find(componentType);
   if ( iter != constructorMap.end() )
   {
      return iter->second();
   }
   else
   {
      return nullptr;
   }
}

ComponentFactory::ConstructorMap& ComponentFactory::getConstructrMap()
{
   static ConstructorMap theMap;
   return theMap;
}

// END implementation of ComponentFactory.
// -----------------------------------------------------

// ComponentManager can use ComponentFactory to 
// construct Components.
class ComponentManager
{
   public:
      ComponentManager() { }
      ~ComponentManager() { }

      IComponent* CreateComponent(std::string const& componentType)
      {
         return ComponentFactory::constructComponent(componentType);
      }
};

// Test code.
// Construct IComponents by using appropriate names.
int main()
{
   ComponentManager m;
   IComponent* ic1 = m.CreateComponent("RenderComponent");
   if ( ic1 == nullptr )
   {
      std::cout << "Unable to construct a Component of type RenderComponent.\n";
   }
   else
   {
      std::cout << "Successfully constructed a Component of type RenderComponent.\n";
   }

   IComponent* ic2 = m.CreateComponent("AnotherTypeOfComponent");
   if ( ic2 == nullptr )
   {
      std::cout << "Unable to construct a Component of type AnotherTypeOfComponent.\n";
   }
   else
   {
      std::cout << "Successfully constructed a Component of type AnotherTypeOfComponent.\n";
   }

   IComponent* ic3 = m.CreateComponent("FooComponent");
   if ( ic3 == nullptr )
   {
      std::cout << "Unable to construct a Component of type FooComponent.\n";
   }
   else
   {
      std::cout << "Successfully constructed a Component of type FooComponent.\n";
   }
}

// Client components.
// Without these, no Component can be constructed.

namespace Module1
{
   class RenderComponent : IComponent
   {
      public:
         RenderComponent() { }
         ~RenderComponent() { }

         static IComponent* constructComponent()
         {
            return new RenderComponent();
         }

         struct Initer
         {
            Initer()
            {
               ComponentFactory::registerComponentConstructor("RenderComponent",
                                                              RenderComponent::constructComponent);
            }
         };
   };

   // The constructor makes sure that
   // RenderComponent::constructComponent() is
   // registered as the function to be called to
   // construct objects of type RenderComponent when
   // the name "RenderComponent" is used.
   // 
   // A different method may be used for the purpose but
   // this seems like a straight forward method to do that.
   static RenderComponent::Initer initer;

}

namespace Module2
{
   class AnotherTypeOfComponent : IComponent
   {
      public:
         AnotherTypeOfComponent() { }
         ~AnotherTypeOfComponent() { }

         static IComponent* constructComponent()
         {
            return new AnotherTypeOfComponent();
         }

         struct Initer
         {
            Initer()
            {
               ComponentFactory::registerComponentConstructor("AnotherTypeOfComponent",
                                                              AnotherTypeOfComponent::constructComponent);
            }
         };
   };

   // The constructor makes sure that
   // AnotherTypeOfComponent::constructComponent() is
   // registered as the function to be called to
   // construct objects of type AnotherTypeOfComponent when
   // the name "AnotherTypeOfComponent" is used.
   static AnotherTypeOfComponent::Initer initer;
}

输出

Successfully constructed a Component of type RenderComponent.
Successfully constructed a Component of type AnotherTypeOfComponent.
Unable to construct a Component of type FooComponent.

答案 1 :(得分:0)

首先,我要感谢R Sahu提供他的答案,但在他的示例中仍然允许用户首先做我想要避免的事情,随机能够创建组件的实例:

IComponent* component = new RenderComponent();

现在我意识到我想要的是不可能的,没有办法限制构造函数/析构函数对用户的访问,也没有限制对ComponentManager的访问。所以要么我的实施是错误的还是不完整的(这是不可能的,但可能的)或者我要求的东西是不合逻辑的(最可能的答案)。

所以我只是选择公开所有内容,只是让随机创建的组件无用,在我的引擎文档中,我将描述你必须使用GameObject :: AddComponent()才能创建和使用组件。

感谢。

相关问题