赞
踩
什么是抽象工厂?
抽象工厂模式是一种创建型设计模式,让你能够保证在客户端程序中创建一系列有依赖的对象组时,无需关心这些对象的类型。
具体来说:
什么是工厂模式?
对于工厂模式和抽象工厂模式的区别,个人认为:
工厂模式——工厂和产品是一对一的关系,即每个工厂只负责一个产品。
抽象工厂模式——工厂和产品是一对多的关系,即每个工厂负责一个产品族。
C++实现一版抽象工厂的例子:
说明:(个人理解总结)
/************************************************************************* > File Name: AbstractFactory.cpp > Author: > Mail: > Created Time: Fri Mar 8 14:51:39 2024 ************************************************************************/ #include <iostream> using namespace std; // Abstarct product(File) class AbstractFile { public: virtual ~AbstractFile() = default; virtual void f_open() = 0; }; class File_Linux : public AbstractFile { public: void f_open() override { // The logic of opening files in Linux. cout << "Opening files successful in Linux !!!" << endl; return ; } }; class File_Windows : public AbstractFile { public: void f_open() override { // The logic of opening files in Windows. cout << "Opening files successful in Windows !!!" << endl; return ; } }; // Abstract product(Process) class AbstractProcess { public: virtual ~AbstractProcess() = default; virtual void create() = 0; }; class Process_Linux : public AbstractProcess { public: void create() override { // The logic of create process in Linux. cout << "Create process successful in Linux !!!" << endl; return ; } }; class Process_Windows : public AbstractProcess { public: void create() override { // The logic of create process in Windows. cout << "Create process successful in Windows !!!" << endl; return ; } }; // Abstarct Factory(Creating Product) class AbstractFactory { public: virtual AbstractFile* CreateFile() = 0; virtual AbstractProcess* CreateProcess() = 0; }; class LinuxFactory : public AbstractFactory { public: AbstractFile* CreateFile() override { return new File_Linux(); } AbstractProcess* CreateProcess() override { return new Process_Linux(); } }; class WindowsFactory : public AbstractFactory { public: AbstractFile* CreateFile() override { return new File_Windows(); } AbstractProcess* CreateProcess() override { return new Process_Windows(); } }; void ClientCode(AbstractFactory *factoy_obj) { AbstractFile *file = factoy_obj->CreateFile(); file->f_open(); AbstractProcess *process = factoy_obj->CreateProcess(); process->create(); delete file; delete process; }; int main() { LinuxFactory ins_linux; ClientCode(&ins_linux); WindowsFactory ins_windows; ClientCode(&ins_windows); return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。