定义:定义一个用于创建对象的接口,让子类决定实例化哪一个类。
举例:学校使用得力品牌的笔。后期学校需要晨光牌的笔,只需换为晨光工厂即可。
类图

客户端
#include <iostream>
#include "ChenguangFactory.h"
#include "DeliFactory.h"
int main(int argc, char *argv[])
{
Factory *factory = new DeliFactory(); // 得力的笔工厂
//Factory *factory = new ChenguangFactory(); // 晨光的笔工厂
Pen *pen1 = factory->constructe();
Pen *pen2 = factory->constructe();
Pen *pen3 = factory->constructe();
// 书写
pen1->write();
pen2->write();
pen3->write();
getchar();
return 0;
}
工厂模式解析

本文解析了工厂模式的概念,通过学校选择不同品牌笔的例子,说明了如何通过定义创建对象的接口,让子类决定实例化哪个类,实现代码的灵活性和扩展性。
2156

被折叠的 条评论
为什么被折叠?



