c语言编程怎么创建一个数组,如何在c中创建一个类数组?

该博客展示了如何使用C++实现一个对象工厂模式,包括基类接口定义、派生类实现以及自动注册到工厂的方法。通过模板类RegisterToFactory自动将类的创建函数注册到工厂中,便于动态创建不同类型的对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include

#include

#include

#include

#include

#include

using namespace std;

// interface

class Base

{

public:

virtual ~Base() { }

virtual int getClassId() = 0;

};

// class A relizes interface Base,has ID == 1 (is used in automatic registration to factory)

class A : public Base

{

public:

const static int ID = 1;

static Base* CreateInstance()

{

return new A();

}

virtual int getClassId()

{

return ID;

}

virtual ~A() { }

};

// class B relizes interface Base,has ID == 2 (is used in automatic registration to factory)

class B : public Base

{

public:

const static int ID = 2;

static Base* CreateInstance()

{

return new B();

}

virtual int getClassId()

{

return ID;

}

virtual ~B() { }

};

// this is the objects factory,with registration only (unregister s not allowed)

class ObjectFactory

{

ObjectFactory() { }

ObjectFactory(ObjectFactory&) { }

public:

virtual ~ObjectFactory() { }

static ObjectFactory& instance()

{

static ObjectFactory objectFactory;

return objectFactory;

}

typedef Base* (*Creator) ();

void registerCreator(int id,Creator creator)

{

registry[id] = creator;

}

Base* CreateById(int id)

{

return registry[id]();

}

private:

map registry;

};

// this template class is used for automatic registration of object's creators

template

struct RegisterToFactory

{

RegisterToFactory(ObjectFactory& factory)

{

factory.registerCreator(T::ID,&T::CreateInstance);

}

};

namespace

{

// automaticaly register creators for each class

RegisterToFactory autoregisterACreator(ObjectFactory::instance());

RegisterToFactory autoregisterBCreator(ObjectFactory::instance());

}

// lets this this solution

int main(int argc,char *argv[])

{

vector ids;

ids.push_back(static_cast(A::ID));

ids.push_back(static_cast(B::ID));

srand(time(0));

for (int i = 0; i < 20; ++i)

{

int randomClasssId = ids[rand() % ids.size()];

auto_ptr testObject(ObjectFactory::instance().CreateById(randomClasssId));

cout << "Object of classId = " << testObject->getClassId() << " has been produced by factory." << endl;

}

system("PAUSE");

return EXIT_SUCCESS;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值