工厂模式:typedef类*(createClassFunction)(void) [英] Factory Pattern: typedef Class *(createClassFunction)(void)

查看:242
本文介绍了工厂模式:typedef类*(createClassFunction)(void)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

typedef Class *(createClassFunction)(void)(或另一个变体是 typedef Class *(__stdcall * CreateClassFunction) / code>)代表?
是什么意思?我应该怎么解释呢?
特别是在工厂模式的上下文中...

What does typedef Class *(createClassFunction)(void) (or another variation is typedef Class* (__stdcall *CreateClassFunction)(void))stand for? What does it mean? How am I supposed to explain it? Especially in the context of Factory Patterns...

推荐答案

读取C类型表达式

createClassFunction 是没有参数并返回 Class * 的函数的typedef。

createClassFunction is a typedef for a function taking no arguments and returning a Class *.

声明,指向这样的函数的指针显然可以作为 Class factory 。用法可能如下:

With that declaration, a pointer to such a funciton can obviously act as factory for a Class. Usage might be as follows:

// 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 ++中实现的函数。

__stdcallis a compiler specific attribute changin the calling convention (how parameters and return value are passed between caller and implementation). This is often important for binary compatibility - e.g. when a Pascal program needs to call a funciton imlemented in C or C++.

问题:

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

The factory function returns a raw pointer. There must be an implicit contract between the factory and the consumer how to free that pointer (e.g. through delete in or example). Using a smart pointer (e.g. shared_ptr) for the return type would allow the factory to determine the deletion policy.

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

The factory, as a function pointer, may not hold state (such as the log file name, it needs to be hard coded in the function, or available globally). using a callable object instead would allow to implement configurable factories.

这篇关于工厂模式:typedef类*(createClassFunction)(void)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆