zoukankan      html  css  js  c++  java
  • 设计模式——抽象工厂模式(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 }
  • 相关阅读:
    Runtime Type Information 运行时类型信息RTTI
    ADO实现单条记录的刷新
    TDataLink类说明
    编程实现文件关联
    咏南的连接池
    关系数据库系统PK面向对象数据库系统
    div+CSS编程技巧
    Hadoop编程笔记(一):Mapper及Reducer类详解
    如何统计博客园的个人博客访问量
    MapReduce编程模型:用MapReduce进行大数据分析
  • 原文地址:https://www.cnblogs.com/dahai/p/2840451.html
Copyright © 2011-2022 走看看