设计模式——工厂方法模式(Factory Method)

  • 创建一工厂接口,实例化延迟至子类(添加新对象,只需增加新的工厂子类)
  • 解决简单工厂违反开闭原则的问题
  • 代码示例:
     1 #include <iostream>
     2 #include <string>
     3 using namespace std;
     4 
     5 //product
     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 private:
    19     Circle() {}
    20     friend class CircleFactory;
    21 };
    22 
    23 class Square : public Shape 
    24 {
    25 public:
    26     void draw() { cout << "Square::draw" << endl; }
    27     ~Square() { cout << "Square::~Square" << endl; }
    28 private:
    29     Square() {}
    30     friend class SqureFactory;
    31 };
    32 
    33 //factory
    34 class Factory
    35 {
    36 public:
    37     virtual Shape* create() = 0;
    38 };
    39 
    40 class CircleFactory : public Factory
    41 {
    42 public:
    43     Shape* create(){return new Circle;}
    44 };
    45 
    46 class SqureFactory : public Factory
    47 {
    48 public:
    49     Shape* create(){return new Square;}
    50 };
    51 
    52 int main() 
    53 {
    54     Factory *pFactory = new CircleFactory;//SqureFactory;
    55 
    56     Shape* pShape = pFactory->create();
    57 
    58     pShape->draw();
    59 
    60     delete pShape;
    61     delete pFactory;
    62 
    63     return 0;
    64 }
posted @ 2012-12-31 11:28  iThinking  阅读(197)  评论(0编辑  收藏  举报