什么是简单工厂模式
它通过一个工厂类根据传入的参数,动态决定创建哪一个产品类的实例。它并不属于 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");
}