读《大话设计模式》---工厂方法模式(factory method)
来源:互联网 发布:南京知臣服饰 编辑:程序博客网 时间:2024/05/29 15:17
工厂方法模式(factory method) :
定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到他的子类。
简单工厂模式和工厂方法模式的区别:
1.简单工厂模式
简单工厂模式的最大优点在于工厂类中包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类,对于客户端来说,去除了与具体产品的依赖。
2.工厂方法模式
工厂方法模式实现时,客户需要决定实例化哪一个工厂来决定产品类,判断选择的问题还是存在的,也就是说:工厂方法把简单工厂的内部逻辑判断移到了客户端代码来实现。你想要加功能,本来是修改工厂类的,而现在是修改客户端。
工厂方法模式的一般形式:
- //定义工厂方法所创建的对象的接口
- class Product
- {
- public:
- void performance();
- };
- //具体的产品,实现Product接口
- class ConcreteProduct : public Product
- {
- public:
- }
- //声明工厂方法,该方法返回一个Product类型的对象
- class Creator
- {
- public:
- virtural Product * Create() = 0;
- }
- //重定义工厂方法以返回一个ConcreteProduct实例
- class ConcreteCreator : public Creator
- {
- public:
- Product * Create()
- {
- return new ConcreteProduct();
- }
- }
一个具体的工厂方法模式的实例:
- #include <iostream>
- using namespace std;
- //志愿者
- class volunteer
- {
- public:
- void regular()
- {
- cout << "维持秩序" << endl;
- }
- void guid()
- {
- cout << "向导" << endl;
- }
- void help()
- {
- cout << "助人为乐" << endl;
- }
- };
- //大学生志愿者
- class undergraduate : public volunteer
- {
- };
- //社会志愿者
- class society : public volunteer
- {
- };
- //抽象工厂(用来生产志愿者,虽然听起来很别扭,呵呵)
- class factory
- {
- public:
- virtual volunteer * CreateVolunteer() = 0;
- };
- //具体工厂(用来生产大学生志愿者)
- class undergraduatefactory : public factory
- {
- public:
- volunteer * CreateVolunteer()
- {
- cout << "创建大学生志愿者:" << endl;
- return new undergraduate();
- }
- };
- //具体工厂(用来生产社会志愿者)
- class societyfactory : public factory
- {
- public:
- volunteer * CreateVolunteer()
- {
- cout << "创建社会志愿者:" << endl;
- return new society();
- }
- };
- int main()
- {
- factory * _afactory = new undergraduatefactory();
- volunteer * _avolunteer = _afactory->CreateVolunteer();
- _avolunteer->guid();
- factory * _bfactory = new societyfactory();
- volunteer * _bvolunteer = _bfactory->CreateVolunteer();
- _bvolunteer->regular();
- return 0;
- }
- 读《大话设计模式》---工厂方法模式(factory method)
- 大话设计模式八:工厂方法模式(factory method)
- 大话设计模式--工厂方法模式 Factory Method -- C++实现
- 设计模式-工厂模式(Factory Method)
- 设计模式-工厂方法模式(factory method)
- 设计模式-工厂方法模式(Factory Method)
- 【设计模式】-工厂方法模式-Factory Method
- 设计模式 工厂方法模式 factory method
- 设计模式 工厂方法模式 Factory Method
- 设计模式之( Factory Method Pattern--工厂方法模式)
- Java设计模式圣经连载(02)-工厂方法(Factory Method)模式
- Java设计模式圣经连载(02)-工厂方法(Factory Method)模式
- 《大话设计模式》--雷锋依然在人间--工厂方法模式<Factory Method>(8)
- 设计模式(1)-工厂方法(Factory Method)
- 【初学设计模式】Factory Method (工厂方法)
- 设计模式学习-Factory Method(工厂方法)
- 设计模式-工厂方法(Factory Method)
- factory method(工厂方法设计模式)
- tablespace 的大小和使用情况
- 关于多行form记录取值的问题!
- 软件项目管理
- 软件项目开发流程以及人员职责
- 没事随便说几句
- 读《大话设计模式》---工厂方法模式(factory method)
- java中/r(回车符)使用后的效果
- 源代码统计工具 - SourceCounter 2.1.14.75版放出
- Use Case 中 include 与 extend 的区别
- 互联网运营的十四个定律
- 笔记081106 UNIX FTP CRONTAB setenv EDITOR = vi export EDITOR = vi BANNER
- PE(Portable Executable) File Format(Chinese) - PE(可移植的可执行文件) 文件格式说明(中文)
- 现实与风度
- 笔记081108 UNIX ORACLE 数据库文件 登录 DESCRIBE NVL @