1. 程式人生 > >c/c++工廠模式

c/c++工廠模式

簡單工廠模式不符合開放關閉原則,擴充套件功能時候需要修改之前的程式碼。所以儘量少用。
結構:
由一個工廠父類(抽象工廠),多個工廠子類(具體工廠),一個產品父類(抽象產品),多個產品子類(具體產品)構成。

C實現方式

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; } typedef people *(*virtual_)(int age); typedef struct factory { virtual_ v; }factory; typedef struct factory_student { factory fa = {get_student}; }factory_student; typedef struct factory_teacher { factory fa = { get_teacher }
; }factory_teacher; void get_date(people *p) { printf("name:%s age: %d\n", p->name, p->age); } int main() { factory_student fa_student; people * student=fa_student.fa.v(20); factory_teacher fa_teacher; people *teacher=fa_teacher.fa.v(50); get_date(student); get_date(teacher); system("pause"); }

c++實現方式

class people
{
public:
	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:
	virtual people * creat(int age)=0;
};

class factory_teacher  :public factory
{
public:
	people * creat(int age)
	{
		return new teacher(age);
	}
};

class factory_student :public factory
{
public:
	people * creat(int age)
	{
		return new student(age);
	}
};


int main()
{
	factory_teacher *fa_teacher = new factory_teacher();
	factory_student *fa_student = new factory_student();
	people *student= fa_student->creat(20);
	student->get_date();
	people *teacher = fa_teacher->creat(50);
	teacher->get_date();
	system("pause");
	return 0;
}