• 设计模式——抽象工厂模式(Abstract Factory)


    • 一组相互关联的对象创建工厂接口(工厂方法模式是为一类对象)
    • 代码示例:
       1 #include <iostream>
       2 #include <string>
       3 using namespace std;
       4 
       5 //shape
       6 class Shape 
       7 {
       8 public:
       9     virtual void draw() = 0;
      10     virtual ~Shape() {}
      11 };
      12 
      13 class Circle : public Shape 
      14 {
      15 public:
      16     void draw() { cout << "Circle::draw" << endl; }
      17     ~Circle() { cout << "Circle::~Circle" << endl; }
      18 };
      19 
      20 class Square : public Shape 
      21 {
      22 public:
      23     void draw() { cout << "Square::draw" << endl; }
      24     ~Square() { cout << "Square::~Square" << endl; }
      25 };
      26 
      27 //color
      28 class Color 
      29 {
      30 public:
      31     virtual void show() = 0;
      32     virtual ~Color() {}
      33 };
      34 
      35 class Red : public Color 
      36 {
      37 public:
      38     void show() { cout << "Red::show" << endl; }
      39     ~Red() { cout << "Red::~Red" << endl; }
      40 };
      41 
      42 class Blue : public Color 
      43 {
      44 public:
      45     void show() { cout << "Blue::show" << endl; }
      46     ~Blue() { cout << "Blue::~Blue" << endl; }
      47 };
      48 
      49 //factory
      50 class AbstractFactory
      51 {
      52 public:
      53     virtual Shape* CreateShape() = 0;
      54     virtual Color* CreateColor() = 0;
      55 };
      56 
      57 class ConcreteFactory1 : public AbstractFactory
      58 {
      59 public:
      60     Shape* CreateShape(){return new Circle;}
      61     Color* CreateColor(){return new Red;}
      62 };
      63 
      64 class ConcreteFactory2 : public AbstractFactory
      65 {
      66 public:
      67     Shape* CreateShape(){return new Square;}
      68     Color* CreateColor(){return new Blue;}
      69 };
      70 
      71 int main() 
      72 {
      73     AbstractFactory *pFactory = new ConcreteFactory1;//ConcreteFactory2;
      74 
      75     Shape* pShape = pFactory->CreateShape();
      76     Color* pColor = pFactory->CreateColor();
      77 
      78     pShape->draw();
      79     pColor->show();
      80 
      81     delete pShape;
      82     delete pColor;
      83     delete pFactory;
      84 
      85     return 0;
      86 }
  • 相关阅读:
    MySQL数据类型
    Linux网络编程:客户端/服务器的简单实现
    初学JAVA
    依据函数名字符串执行函数
    Windows Server 2012学习文档
    DELPHI WEBSERVICE
    常用函数、常量、类型记录
    CAD2007_DWG转PDF
    MCU_头文件编写
    MCU_存储器
  • 原文地址:https://www.cnblogs.com/dahai/p/2840451.html
Copyright © 2020-2023  润新知