2022/03/06 抽象工厂模式
-
复习食用指南:
1.看UML有一个基本概念
2.把代码跑一下,一步一步跑
几张UML看一下基本的关系
代码
借鉴了一下设计模式相关网站的代码
https://refactoringguru.cn/design-patterns/abstract-factory
这个是C++的,不是java
#include<iostream>
class phone {
public:
virtual ~phone() {};
virtual std::string phone_doing() const = 0;
};
class xiaomi_phone: public phone {
public:
std::string phone_doing() const override {
return "The result of the product A1.";
}
};
class huawei_phone : public phone {
std::string phone_doing() const override {
return "The result of the product A2.";
}
};
class computer {
public:
virtual ~computer() {};
virtual std::string computer_doing1() const = 0;
virtual std::string computer_doing2(const phone& collaborator) const = 0;
};
class xiaomi_computer : public computer {
public:
std::string computer_doing1() const override {
return "The result of the product B1.";
}
std::string computer_doing2(const phone& collaborator) const override {
const std::string result = collaborator.phone_doing();
return "The result of the B1 collaborating with ( " + result + " )";
}
};
class huawei_computer : public computer {
public:
std::string computer_doing1() const override {
return "The result of the product B2.";
}
std::string computer_doing2(const phone& collaborator) const override {
const std::string result = collaborator.phone_doing();
return "The result of the B2 collaborating with ( " + result + " )";
}
};
//创造工厂的工厂
class AbstractFactory {//这里面都是一个工厂应该要做的事情
public:
virtual phone* Createphone() const = 0;
virtual computer* Createcomputer() const = 0;
};
class xiaomi : public AbstractFactory {//小米厂
public:
phone* Createphone() const override {
return new xiaomi_phone();
}
computer* Createcomputer() const override {
return new xiaomi_computer();
}
};
class huawei : public AbstractFactory {//华为厂
public:
phone* Createphone() const override {
return new huawei_phone();
}
computer* Createcomputer() const override {
return new huawei_computer();
}
};
//xx是什么取决于传进来的工厂是哪一个
void ClientCode(const AbstractFactory& factory) {
const phone* product_a = factory.Createphone();//生产出一个xx牌手机
const computer* product_b = factory.Createcomputer();//生产出一个xx牌电脑
std::cout << product_b->computer_doing1() << "\n";//跑到xx牌电脑(具体类去运行相关函数)
std::cout << product_b->computer_doing2(*product_a) << "\n";
delete product_a;
delete product_b;
}
int main() {
std::cout << "Client: Testing client code with the first factory type:\n";
xiaomi* f1 = new xiaomi();//建造了一个xx牌工厂
ClientCode(*f1);
delete f1;
std::cout << std::endl;
std::cout << "Client: Testing the same client code with the second factory type:\n";
huawei* f2 = new huawei();//建造了一个xx牌工厂
ClientCode(*f2);
delete f2;
return 0;
}