介绍:
原型模式是一种创建型设计模式,使你可以通过复制原型来创建一个一模一样的新的对象,无需考虑创建过程,数据类型等内容;
作用:
创建一个与原型一模一样的对象;
解决问题:
- 即使原型的状态有所改变,也可以创建出与其当前状态一致的对象
- 省去了创建对象的复杂操作,不必关注创建对象的具体过程
类比:
老师打印试卷,拿着原版试卷,可以复制出任意数量的试卷,原版试卷即为原型;
代码示例:
#include
#include
#include
#define VAR(name, id) name##id
typedef struct Paper
{
char* teacher_name;
int class;
char* question;
struct Paper* (*copy)(struct Paper* pPaper);
} paper_t;
/*原型的复制接口*/
paper_t* paper_copy(paper_t* pPaper)
{
paper_t* copy = (paper_t*)malloc(sizeof(paper_t));
memcpy(copy, pPaper, sizeof(paper_t));
return copy;
}
paper_t* clone(paper_t* pPaper)
{
return pPaper->copy(pPaper);
}
void main(void)
{
/*定义原型*/
paper_t origin_paper = {"Li", 5, "1 + 1 = ?", paper_copy};
/*复制10份试卷*/
for(int i = 1; i <= 10; i++)
{
paper_t* VAR(paper, i) = clone(&origin_paper);
printf("paper_%d => name: %s, class: %d, question: %sr
",
i, VAR(paper, i)->teacher_name, VAR(paper, i)->class, VAR(paper, i)->question);
}
}
输出:
paper_1 => name: Li, class: 5, question: 1 + 1 = ?
paper_2 => name: Li, class: 5, question: 1 + 1 = ?
paper_3 => name: Li, class: 5, question: 1 + 1 = ?
paper_4 => name: Li, class: 5, question: 1 + 1 = ?
paper_5 => name: Li, class: 5, question: 1 + 1 = ?
paper_6 => name: Li, class: 5, question: 1 + 1 = ?
paper_7 => name: Li, class: 5, question: 1 + 1 = ?
paper_8 => name: Li, class: 5, question: 1 + 1 = ?
paper_9 => name: Li, class: 5, question: 1 + 1 = ?
paper_10 => name: Li, class: 5, question: 1 + 1 = ?