工厂模式:typedef Class *(createClassFunction)(void)

Factory Pattern: typedef Class *(createClassFunction)(void)

本文关键字:void createClassFunction Class 模式 typedef 工厂      更新时间:2023-10-16

typedef Class *(createClassFunction)(void)(或typedef Class* (__stdcall *CreateClassFunction)(void)的另一种变体)代表什么?这是什么意思?我该怎么解释呢?

读取C类型表达式

createClassFunction是一个不接受参数并返回Class *的函数的类型定义。

有了这个声明,指向这样一个函数的指针显然可以作为Class工厂。用法可能如下:
// the class factory
Class * MostTrivialFactoryKnownToMan()
{
 return new Class;
}
// another class factory
Class * CreateClassWithLog()
{
   ClassWithLog * p = new ClassWithLog; // derived from Class
   p->SetLogFile("log.txt");
   return p;
}
// code consuming the class factory
void PopulateStars(createClassFunction * factory)
{
   // creates many instances of `Class` through `factory`
   Sky * sky = GetSky();
   for(int i=0; i<sky->GetStarCount(); ++i)
   {
      Class * inhabitant = (*factory)();
      sky->GetStar(i)->SetInhabitant(inhabitant);
   }
}
// code deciding which factory to use
const bool todayWeWriteALog = (rand() %2) != 0;
createClassFunction * todaysFactory = todayWeWriteALog ?
   &MostTrivialFactoryKnownToMan : 
   &CreateClassWithLog);
PopulateStars(factory);

__stdcall是在调用约定(参数和返回值如何在调用者和实现之间传递)中特定于编译器的属性更改。这通常对二进制兼容性很重要——例如,当Pascal程序需要调用用C或c++实现的函数时。

问题:

工厂函数返回一个原始指针。在工厂和消费者之间必须有一个如何释放指针的隐式契约(例如,通过或示例中的delete)。使用智能指针(例如shared_ptr)作为返回类型将允许工厂决定删除策略。

作为函数指针的工厂可能不保存状态(例如日志文件名,它需要在函数中硬编码,或者全局可用)。使用可调用对象将允许实现可配置工厂。