c/c++简单工厂模式

什么是简单工厂模式

它通过一个工厂类根据传入的参数,动态决定创建哪一个产品类的实例。它并不属于 23 种 GoF 设计模式之一,但常常被人们使用。
结构:
由一个工厂,一个产品父类(抽象产品),多个产品子类(具体产品)构成。
流程:
根据唯一的工厂对象中的函数参数,判断并自动new出一个产品子类对象并返回其产品父类的指针,这样利用父类的指针执行父类的虚函数,就可以动态绑定子类的重写函数,从而实现多态。

c实现方式

在这个程序中,有工厂结构体factory,一个产品父结构体people,两个产品子结构体student,teacher以及一些结构体操作函数。main中,根据工厂的参数,获得想要的产品,打印出相应产品的数据。

enum enum_people
{
	STUDENT = 0,
	TEACHER,
};
typedef struct people
{
	int age;
	char name[20];
};

typedef struct student
{
	people p;
	//add other
}student ,*pstudent;
people*  get_student(int age)
{
	student *p = (student *)malloc(sizeof(student));
	((people *)p)->age = age;
	strcpy_s((((people *)p)->name),"student");
	return  (people* )p;
}


typedef struct teacher
{
	people p;
	//add other
}teacher, *pteacher;
people*  get_teacher(int age)
{
	teacher *p = (teacher *)malloc(sizeof(teacher));
	((people *)p)->age = age;
	strcpy_s((((people *)p)->name), "teacher");
	return  (people*)p;
}


static people* getpeople(enum enum_people e,int age)
{
	switch (e)
	{
	case STUDENT:
		return  get_student(age);
		break;
	case TEACHER:
		return get_teacher(age);
	default:
		break;
	}
}

void get_date(people *p)
{
	printf("name:%s  age: %d\n", p->name, p->age);
}
int main()
{
	people* t = getpeople(TEACHER, 50);
	get_date(t);
	people* s = getpeople(STUDENT, 20);
	get_date(s);
	system("pause");
}

c++实现方式

在这个程序中,有工厂类factory,一个产品父类people,两个产品子类student,teacher。
main中,根据工厂的参数,获得想要的产品,打印出相应产品的数据。

class people
{
public:
	people() {};
	~people() {};
	virtual void get_date() = 0;
protected:
	int age;
	std::string name;
};

class student :public people
{
public:
	student(int age) { name = { "student" }, people::age = age; };
	~student() {};
	void get_date()
	{
		std::cout << "name:" << name.c_str() << "age: " << age << std::endl;
	}
};

class teacher :public people
{
public:
	teacher(int age) { name = { "teacher" }, people::age = age; };
	~teacher() {};
	void get_date()
	{
		std::cout << "name:" << name.c_str() << "age: " << age << std::endl;
	}
};
 class factory
{
public:
	enum enum_people
	{
		STUDENT = 0,
		TEACHER,
	};
	static people* get_people(enum enum_people e,int age)
	{
		switch (e)
		{
		case STUDENT:
			return  new student(age);
			break;
		case TEACHER:
			return new teacher(age);
			break;
		}
	}
	 factory() {};
	 ~factory() {};
};
int main()
{
	people *t= factory::get_people(factory::enum_people::TEACHER,50);
	t->get_date();
	people *s = factory::get_people(factory::enum_people::STUDENT,20);
	s->get_date();
	system("pause");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

工农村贴膜小哥

我倒是要看看是那个憨憨在给我打

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值