简单工厂模式不符合开放关闭原则,扩展功能时候需要修改之前的代码。所以尽量少用。
结构:
由一个工厂父类(抽象工厂),多个工厂子类(具体工厂),一个产品父类(抽象产品),多个产品子类(具体产品)构成。
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;
}