工厂模式属于创建型模式
特点:被实例化的子类
#include <iostream>
using namespace std;
//抽象类
class product {
public:
int width, height;
public:
virtual ~product()=0;
void print();
protected:
() = default;
product(int width,int height):width(width),height(height) {
product
}
};
::~product() {
product<< "~product()" << endl;
cout }
void product::print() {
<< width << " " << height << endl;
cout }
class apple :public product {
public:
():product(12,21) {
apple
}
~apple() {
<< "~apple()" << endl;
cout };
};
class orange :public product {
public:
() :product(12, 12) {
orange
}
~orange() {
<< "~orange()" << endl;
cout }
};
//抽象类
class factory {
public:
virtual ~factory()=0;
virtual product* create_apple()=0;
virtual product* create_orange() = 0;
protected:
()=default;
factory};
::~factory() {
factory<< "~factory()" << endl;
cout }
class product_factory :public factory {
public:
~product_factory();
()=default;
product_factory* create_apple()override;
product* create_orange()override;
product};
::~product_factory() {
product_factory<< "~product_factory()" << endl;
cout }
* product_factory::create_apple() {
productreturn new apple();
}
* product_factory::create_orange() {
productreturn new orange();
}
int main() {
* m_factory = new product_factory();
factory* m_apple=m_factory->create_apple();
product* m_orange = m_factory->create_orange();
productm_apple->print(); //12 21
m_orange->print();//12 12
delete m_factory; //~product_factory() ~factory()
delete m_apple; //~apple() ~product()
delete m_orange; //~orange() ~product()
return 0;
}