博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
多态工厂
阅读量:5148 次
发布时间:2019-06-13

本文共 2466 字,大约阅读时间需要 8 分钟。

思考: 注册类的时候仍然是需要手动添加到初始化类中,有没有办法通过传递类名,或者以类字符串的形式注册新类? #include 
#include
#include
#include
#include
#include
//#include "../purge.h"using namespace std;class Shape {public: virtual void draw() = 0; virtual void erase() = 0; virtual ~Shape() {}};//base classclass ShapeFactory{private: virtual Shape* create() = 0; //
<类名称--该类的创建工厂>
static map
factories;public: virtual ~ShapeFactory() {} friend class ShapeFactoryInitializer; class BadShapeCreation : public logic_error { public: BadShapeCreation(string type) : logic_error("Cannot create type " + type) {} }; // 通过类名称找到类的创建工厂,调用create()方法对象 static Shape* createShape(const string& id) throw(BadShapeCreation) { if(factories.find(id) != factories.end()) return factories[id]->create(); else throw BadShapeCreation(id); }};// Define the static object:map
ShapeFactory::factories;class Circle : public Shape {private: Circle() { } // Private constructor friend class ShapeFactoryInitializer; // 当前类的创建工厂,实际上就是为了封装create方法,即“方法对象” class Factory : public ShapeFactory { public: // 实现当前对象的创建 Shape* create() { return new Circle; } // 这一句似乎没多大意义,除非将将Facotry()设为私有 friend class ShapeFactoryInitializer; };public: void draw() { cout << "Circle::draw" << endl; } void erase() { cout << "Circle::erase" << endl; } ~Circle() { cout << "Circle::~Circle" << endl; }};class Square : public Shape { Square() {} // Private constructor friend class ShapeFactoryInitializer; class Factory : public ShapeFactory { public: Shape* create() { return new Square; } friend class ShapeFactoryInitializer; };public: void draw() { cout << "Square::draw" << endl; } void erase() { cout << "Square::erase" << endl; } ~Square() { cout << "Square::~Square" << endl; }};//单例模式class ShapeFactoryInitializer {private: static ShapeFactoryInitializer si; ShapeFactoryInitializer() { ShapeFactory::factories["Circle"]= new Circle::Factory; ShapeFactory::factories["Square"]= new Square::Factory; } ~ShapeFactoryInitializer() { map
::iterator it = ShapeFactory::factories.begin(); while(it != ShapeFactory::factories.end()) delete it++->second; }};ShapeFactoryInitializer ShapeFactoryInitializer::si;int main() { try { Shape *circle_s = ShapeFactory::createShape("Circle"); circle_s->draw(); circle_s->erase(); } catch(ShapeFactory::BadShapeCreation e) { cout << e.what() << endl; return EXIT_FAILURE; } return 0;}

 

转载于:https://www.cnblogs.com/yigan/p/3345330.html

你可能感兴趣的文章
CSS3笔记4
查看>>
约瑟夫问题
查看>>
DOM节点类型
查看>>
初识socket
查看>>
Hive(二)hive的基本操作
查看>>
[笔记] SQL性能优化 - 常用语句(一)
查看>>
openvino安装踩坑记
查看>>
html03
查看>>
LINQ语法详解
查看>>
The folder is already a source folder
查看>>
App 组件化/模块化之路——Android 框架组件(Android Architecture Components)使用指南
查看>>
Java里的日期和时间学习
查看>>
securecrt 上传下载
查看>>
公共技术点之 Java 反射 Reflection
查看>>
DICOM:DICOM3.0网络通信协议
查看>>
免费好用的web应用托管平台-续
查看>>
分享:FIFO 同步、异步以及Verilog代码实现
查看>>
二分查找算法
查看>>
《构建之法》读书笔记2
查看>>
enum 枚举一般用法 dotnet
查看>>