设计模式——简单工厂模式
概念
- 设计模式是前人设计经验的总结、稳定、拓展性更强的一系列编程思想、
- 代码更容易让他人理解、保证代码的可靠性、程序的重要性。
对象和类
- 类是一种用户 定义的引用数据类型,也称类类型(相当于结构体)
- 对象是类的一种具象
struct Animal{
int age;
int sex;
void (*peat)();
void (*pbeat)();
};
struct Animal dog;
struct Animal cat;
#include <stdio.h>
struct Animal{
int age;
int sex;
void (*peat)();
void (*pbeat)();
};
void dogEat()
{
printf("dog eat\n");
}
void catEat()
{
printf("cat eat\n");
}
void personEat()
{
printf("person eat\n");
}
int main()
{
struct Animal dog;
struct Animal cat;
struct Animal person;
dog.peat = dogEat;
cat.peat = catEat;
person.peat = personEat;
return 0;
}
工厂模式
- 工厂模式(Factory Pattern)是最常用的设计模式之一
- 该设计模式属于创建型模式,它提供了一种创建对象的最佳方式
- 在工厂模式中,我们在创建对象时不会对客户暴露创建逻辑,并且通过使用一个共同的接口来指向新创建的对象。