在设计模式中,简单工厂模式中一个是Product类(产品类),一个是ProductManager类(工厂类),而两个类互相引用了,形成了环形引用
,而前向声明可以解决这个问题,但是在应用前向声明
的时候需要注意一点就是,声明仅仅是声明,并没有实现,因此不能调用声明的变量的方法或者实现该类
。举例如下:
去掉注释就是正确的前向声明,没有去掉注释就是错误的前向声明应用
编译
g++ main.cpp product.cpp product_manager.cpp -I. -std=c++11
文件
product.h
#pragma once
#include <string>
using namespace std;
class ProductManager;
// Product
class Product {
public:
Product(ProductManager *_manager, string _name);
string getName();
void setName(string _name);
private:
string name;
bool canChanged = false;
};
product.cpp
#include "product.h"
Product::Product(ProductManager *_manager, string _name) {
// error: invalid use of incomplete type 'class ProductManager'
// if(_manager->isCreateProduct()) {
// canChanged = true;
// this->name = _name;
// }
}
string Product::getName() {
return name;
}
void Product::setName(string _name) {
if(canChanged) {
this->name = _name;
}
}
product_manager.h
#pragma once
#include <string>
using namespace std;
class Product;
class ProductManager {
public:
Product* createProduct(string _name);
void abandonProduct(Product *p);
void editProduct(Product *p, string _name);
bool isCreateProduct();
private:
bool isPermittedCreate = false;
};
product_manager.cpp
#include "product_manager.h"
Product* ProductManager::createProduct(string _name) {
isPermittedCreate = true;
// error: invalid use of incomplete type 'class Product'
// Product *p = new Product(this, _name);
// return p;
return NULL;
}
void ProductManager::abandonProduct(Product *p) {
// warning: possible problem detected in invocation of delete operator
// delete p;
}
void ProductManager::editProduct(Product *p, string _name) {
// error: invalid use of incomplete type 'class Product'
//p->setName(_name);
}
bool ProductManager::isCreateProduct() {
return isPermittedCreate;
}
main.cpp
#include <iostream>
#include <string>
#include "product_manager.h"
#include "product.h"
using namespace std;
int main()
{
return 0;
}
当然,工厂模式真正的实现并非如此潦草,肯定需要结合多态。