zoukankan      html  css  js  c++  java
  • 设计模式——工厂方法模式(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 }
  • 相关阅读:
    http服务读取配置文件,交叉编译
    etcd增删改查
    初始
    20141017--类型String类
    20141017--异常语句try-catch
    20141017--循环语句whlie,do
    20141017--循环语句for 穷举
    20141016--for 菱形
    20141016--for 兔子
    20141015--for语句1
  • 原文地址:https://www.cnblogs.com/dahai/p/2840390.html
Copyright © 2011-2022 走看看