• 设计模式——工厂方法模式(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 }
  • 相关阅读:
    死锁
    不能复制文件到服务器
    JWT
    身份验证
    依赖注入
    ml.net
    swift 枚举、结构、类
    nginx 负载均衡
    sql 时间函数大全
    更新SVN时提示要清理,但清理失败,乱码得解决方案
  • 原文地址:https://www.cnblogs.com/dahai/p/2840390.html
Copyright © 2020-2023  润新知