0 抽象工厂
1、接着上次总结,前面提到当需要生产一个新的产品(和旧产品存在某种联系)但是不希望新建一个工厂,而是在旧的工厂中加入一个新的生产线,需要引入抽象工厂模式
2、抽象工厂模式和工厂方法模式类似,区别在于
a、产品类增加了不同基类,不同基类下派生不同产品
b、工厂不增加基类,但是在每个工厂中增加纯虚函数(相当于工厂中增加生产线)
3、在具体生产产品时,先选择工厂,在选择工厂中的生产线即可
#include <iostream>
using namespace std;
class ProductA
{
public:
virtual void ShowYouself() = 0;
private:
};
class ProductA1 : public ProductA
{
public:
void ShowYouself()
{
cout << "创建了A1" << endl;
}
private:
};
class ProductA2 : public ProductA
{
public:
void ShowYouself()
{
cout << "创建了A2" << endl;
}
private:
};
//**************************ProtuctB*******************************
class ProductB
{
public:
virtual void ShowYouself() = 0;
private:
};
class ProductB1 : public ProductB
{
public:
void ShowYouself()
{
cout << "创建了B1" << endl;
}
private:
};
class ProductB2 : public ProductB
{
public:
void ShowYouself()
{
cout << "创建了B2" << endl;
}
private:
};
//**************************Fectory********************************
class Fectory
{
public:
virtual ProductA *CreateProtectA() = 0;
virtual ProductB *CreateProtectB() = 0;
};
class Fectory1 : public Fectory
{
public:
ProductA *CreateProtectA()
{
cout << "来到工厂1,这条生产线生产A1" << endl;
return new ProductA1;
}
ProductB *CreateProtectB()
{
cout << "来到工厂1,这条生产线生产B1" << endl;
return new ProductB1;
}
};
class Fectory2 : public Fectory
{
public:
ProductA *CreateProtectA()
{
cout << "来到工厂2,这条线生产A2" << endl;
return new ProductA2;
}
ProductB *CreateProtectB()
{
cout << "来到工厂2,这条线生产B2" << endl;
return new ProductB2;
}
};
int main(void)
{
Fectory *fectory1 = new Fectory1();
Fectory *fectory2 = new Fectory2();
ProductA *productA1 = fectory1->CreateProtectA();
ProductB *productB1 = fectory1->CreateProtectB();
productA1->ShowYouself();
productB1->ShowYouself();
ProductA *productA2 = fectory2->CreateProtectA();
ProductB *productB2 = fectory2->CreateProtectB();
productA2->ShowYouself();
productB2->ShowYouself();
if (productA1 != NULL)
{
cout << "productA1被回收" << endl;
delete productA1;
productA1 = NULL;
}
if (productB1 != NULL)
{
cout << "productB1被回收" << endl;
delete productB1;
productB1 = NULL;
}
if (productA2 != NULL)
{
cout << "productA2被回收" << endl;
delete productA2;
productA2 = NULL;
}
if (productB2 != NULL)
{
cout << "productB2被回收" << endl;
delete productB2;
productB2 = NULL;
}
if (fectory1 != NULL)
{
cout << "fectory1被回收" << endl;
delete fectory1;
fectory1 = NULL;
}
if (fectory2 != NULL)
{
cout << "fectory2被回收" << endl;
delete fectory2;
fectory2 = NULL;
}
system("pause");
return 0;
}
4、工厂设计模式到此告一段落,实际编程时设计模式的使用可以让代码更具逻辑性和可读性,不过可以想到有一个问题就是,万万不可为了使用设计模式而去使用设计模式,应该是模式往实际上靠,而不是实际向模式上靠,不过说简单,具体的应用还得日后积累经验