• 设计模式——工厂方法模式(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 }
  • 相关阅读:
    μC/OS-III---I笔记5---多值信号量
    μC/OS-III---I笔记4---软件定时器
    μC/OS-III---I笔记3---时间管理
    μC/OS-III---I笔记2---实钟节拍
    μC/OS-III---I笔记1---概述
    Cortex-M系列内核 启动文件分析
    C语言中函数的调用方式
    const,volatile,static,typdef,几个关键字辨析和理解
    java注解细节
    java枚举细节
  • 原文地址:https://www.cnblogs.com/dahai/p/2840390.html
Copyright © 2020-2023  润新知