优化代码#include <iostream> #include<memory> #include<string> using namespace std; class Factory { public: virtual void makeProduct(string st) = 0; protected: Product* product; }; class Factory1 : public Factory { public: void makeProduct(string st) { cout << "工厂1创建"+st; } }; class Factory2 : public Factory { public: void makeProduct(string st) { cout << "工厂2创建"+st; } }; class Product{ public: void setFactory(Factory* fac) { this->factory = fac; }; virtual void Show() = 0; protected: Factory* factory; }; class ProductA : public Product { public: void Show() { string st="产品A"; this->factory->makeProduct(st); }; }; class ProductB : public Product { public: void Show() { string st = "产品B"; this->factory->makeProduct(st); } }; int main() { Factory* factory1; Product* productA; productA = new ProductA; factory1 = new Factory1; productA->setFactory(factory1); return 0; }
时间: 2023-07-15 11:12:31 浏览: 43
这段代码看起来已经是一个比较完整的工厂模式了,不过还有一些可以优化的地方。
1. 使用工厂函数代替工厂类
工厂类在这里只有一个纯虚函数,可以直接使用函数来代替。
2. 使用智能指针避免内存泄漏
在代码中使用了 new 操作符来分配内存,需要手动释放,容易造成内存泄漏。可以使用智能指针来自动管理内存,避免这个问题。
3. 将 string 字符串传参改为 const 引用
在代码中,每次传递 string 字符串时都会进行复制,可以使用 const 引用来避免这个问题。
下面是优化后的代码:
```
#include <iostream>
#include <memory>
using namespace std;
class Product {
public:
virtual void Show() = 0;
};
class ProductA : public Product {
public:
void Show() override {
cout << "产品A" << endl;
}
};
class ProductB : public Product {
public:
void Show() override {
cout << "产品B" << endl;
}
};
using FactoryFunction = unique_ptr<Product> (*)();
unique_ptr<Product> Factory1() {
return make_unique<ProductA>();
}
unique_ptr<Product> Factory2() {
return make_unique<ProductB>();
}
int main() {
auto productA = Factory1();
auto productB = Factory2();
productA->Show();
productB->Show();
return 0;
}
```
在优化后的代码中,使用了智能指针来管理内存,使用了工厂函数来代替工厂类,并且将传递字符串的方式改为了 const 引用。这样可以更好地提高代码的可读性和可维护性。