zoukankan      html  css  js  c++  java
  • 设计模式——简单工厂模式(Simple Factory)

    • 即将对象创建封装到工厂类中,用户传递参数给工厂对象,获取相应对象。
    • 通过多态,将用户与具体对象隔离开
    • 代码示例
       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 SimpleFactory;
      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 SimpleFactory;
      31 };
      32 
      33 //factory
      34 class SimpleFactory
      35 {
      36 public:
      37     static Shape* create(const string& type)
      38     {
      39         if(type == "Circle") return new Circle;
      40         if(type == "Square") return new Square;
      41         //...
      42         return NULL;
      43     }
      44 };
      45 
      46 int main() 
      47 {
      48     Shape* pShape1 = SimpleFactory::create("Circle");
      49     Shape* pShape2 = SimpleFactory::create("Square");
      50 
      51     pShape1->draw();
      52     pShape2->draw();
      53 
      54     delete pShape1;
      55     delete pShape2;
      56 
      57     return 0;
      58 }
  • 相关阅读:
    python3+requests库框架设计03-请求重新封装
    python3+requests库框架设计02-封装日志类
    [patl2-001]紧急救援
    [patl1-046]整除光棍
    latex学习
    matlab基础功能实践
    dll注入及卸载实践
    编译原理大作业暂存
    12.24逆向工程上机作业整理
    [poj1703]Find them, Catch them(种类并查集)
  • 原文地址:https://www.cnblogs.com/dahai/p/2839868.html
Copyright © 2011-2022 走看看