zoukankan      html  css  js  c++  java
  • 1 创建型模式-----简单工厂模式

    1.1 模式定义

    简单工厂模式:将创建不同对象的代码封装到具体产品类中;

    将创建这些具体产品类的公共代码封装到到抽象产品类中;

    定义一个工厂类,该类的静态方法可以根据不同参数创建不同的具体产品实例。

    模式要点:需要什么类型的产品,只需传入一个正确的参数,就可以获得一个对应的实例。

    1.2 模式结构图

     

    1.3 模式角色

    抽象产品Product: 具体产品类的父类,封装了各种具体产品的公共方法。

    具体产品ConcreteProduct: 需要实例化的类。

    工厂类Factory: 简单工厂模式的核心,负责创建所有具体产品的实例。

    1.4 代码实现

    bt_简单工厂模式.h

     1 #ifndef SFP_H
     2 #define SFP_H
     3 #include <string.h>
     4 #include <iostream>
     5 
     6 using namespace std;
     7 
     8 /*
     9     定义抽象产品类
    10 */
    11 class Product
    12 {
    13 public:
    14     virtual ~Product(){}
    15 };
    16 
    17 /*
    18     定义具体产品类
    19 */
    20 class ConcreteProductA : public Product
    21 {
    22 public:
    23     ConcreteProductA();
    24 };
    25 ConcreteProductA::ConcreteProductA()
    26 {
    27     cout << "创建具体产品A" << endl;
    28 }
    29 
    30 class ConcreteProductB : public Product
    31 {
    32 public:
    33     ConcreteProductB();
    34 };
    35 ConcreteProductB::ConcreteProductB()
    36 {
    37     cout << "创建具体产品B" << endl;
    38 }
    39 
    40 /*
    41     定义工厂类
    42 */
    43 class Factory
    44 {
    45 public:
    46     static Product* createProduct(const string& type)
    47     {
    48         if(type.compare("A") == 0)
    49         {
    50             return new ConcreteProductA;
    51         }
    52         if(type.compare("B") == 0)
    53         {
    54             return new ConcreteProductB;
    55         }
    56         else
    57         {
    58             cout << "unknown product type" << endl;
    59             return NULL;
    60         }
    61     }
    62 };
    63 #endif // SFP_H

    bt_简单工厂模式.cpp

     1 #include "bt_简单工厂模式.h"
     2 #include <iostream>
     3 using namespace std;
     4 
     5 int main()
     6 {
     7     cout << "***** 简单工厂模式测试 *****" << endl;
     8     Product* product = NULL;
     9     product = Factory::createProduct("A");
    10 
    11     delete product;
    12     
    13     return 0;
    14 }          
    
    

    1.5 模式总结

    简单工厂模式提供了用于创建对象的工厂类,将对象的创建和使用分量开来,其特点如下:

    优点:

    分离对象的创建和使用;用户只需通过具体产品对应的参数即可创建实例对象。

    缺点:

    工厂类职责过重;系统扩展困难,增加新产品必须修改工厂逻辑。

    适用场景:

    具体产品类比较少且稳定的情况。

     

                                                          

  • 相关阅读:
    ts 问号点 ?.
    moment获取本月、上个月、近三个月时间段
    iframe优缺点
    Git问题解决方案:不建议在没有为偏离分支指定合并策略时执行pull操作(Pulling without specifying how to reconcile divergent branches)
    Mac上git自动补全功能
    webstorm 使用积累
    什么是EPG?
    chrome浏览器devtools切换主题(亮色,暗色)
    python—requests的基本使用
    Chrome Devtool Performance
  • 原文地址:https://www.cnblogs.com/benxintuzi/p/4524772.html
Copyright © 2011-2022 走看看