【设计模式】创建型模式——简单工厂模式

【设计模式】创建型模式——简单工厂模式,第1张

1. 概念

简单工厂模式(Simple Factory),又称为静态工厂模式(Static Factory)。简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例,是工厂模式系列中最简单实用的设计模式

简单工厂模式并不属于23种设计模式之一,但其结构简单,便于理解,在软件设计中被大量应用

2. 基本结构

简单工厂模式的基本结构如下UML图所示:

3. 基本代码结构

这里以C++为例给出实现代码:

class Product {
	
};

class Product1: public Product {
	
};

class Product2: public Product {
	
};

class SimpleFactory {
public:
	static Product createProduct(string productClass) {
		switch(productClass){
			case "class1":
				return new Product1();
				break;
			case "class2":
				return new Product2();
				break;
			default:
				return null;
		}
	}
};
4. demo 4.1 应用描述

随着多媒体技术的不断发展,各类多媒体格式层出不穷,每种格式通常都需要特定的解码器解码后才能播放出来。以Windows自带的媒体播放器(MediaPlayer)为例,它可以用来播放多种音频及视频格式。无论想听.mp3格式的音乐还是.wma格式的音乐,都可以用一个MediaPlayer打开并进行回放。以视听者的角度来看,这些文件没有差别,但其依赖于特定的解码器类型(Decoder),只有使用对应的解码器进行解码才能将该多媒体回放出来

现假定有.mp3.wma两种格式的音频文件,尝试模仿MediaPlayer的工作过程

4.2 实现代码
#include "bits/stdc++.h"

using namespace std;

class Decoder {
public:
    virtual void decode() = 0;
};

class Mp3Decoder : public Decoder {
public:
    string fileName;

    Mp3Decoder(string fileName) {
        this->fileName = fileName;
        this->decode();
    }

    void decode() override {
        cout << "[type: .mp3] " << this->fileName << " start decoding" << endl;
    }
};

class WmaDecoder : public Decoder {
public:
    string fileName;

    WmaDecoder(string fileName) {
        this->fileName = fileName;
        this->decode();
    }

    void decode() override {
        cout << "[type: .wma] " << this->fileName << " start decoding" << endl;
    }
};


vector<string> split(const string &str, const string &delim) {
    vector<string> res;
    if (str.empty()) return res;

    string strs = str + delim;
    size_t pos;
    size_t size = strs.size();

    for (int i = 0; i < size; ++i) {
        pos = strs.find(delim, i);
        if (pos < size) {
            string s = strs.substr(i, pos - i);
            res.push_back(s);
            i = pos + delim.size() - 1;
        }

    }
    return res;
}

class DecoderSimpleFactory {
public:
    static Decoder *createDecoder(string fileName) {
        vector<string> fileNameParts = split(fileName, ".");
        string suffix = fileNameParts[fileNameParts.size() - 1];
        if (suffix == "mp3") {
            return new Mp3Decoder(fileName);
        } else if (suffix == "wma") {
            return new WmaDecoder(fileName);
        } else {
            return nullptr;
        }
    }
};

int main() {
    string fileName = "One Last Kiss.mp3";
    DecoderSimpleFactory::createDecoder(fileName);
    return 0;
}
5. 优点
  • 结构简单,易于理解
  • 能根据客户端的选择条件动态实例化相关的类
  • 削弱了对具体产品类的依赖,有利于整体结构的优化
6. 缺点
  • 高内聚做的并不好
  • 具体产品类增多时,可能会导致工厂类也要做出相应修改
7. 适用场合

当多个具体类具有相似的特征,且希望而客户端可以免除直接创建产品对象时,适合用简单工厂模式

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1325649.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-12
下一篇2022-06-12

发表评论

登录后才能评论

评论列表(0条)

    保存