代码演示:
********************************************
Factory.h janvyking999
********************************************
class Product {
public:
Product() {}
virtual ~Product() {}
};
class ConcreateProduct:public Product {
public:
ConcreateProduct();
virtual ~ConcreateProduct();
};
class Creator {
public:
Creator() {}
virtual ~Creator() {}
void anOperation();
protected:
virtual Product* FactoryMethod() = 0;
};
class ConcreateCreator:public Creator {
public:
ConcreateCreator();
virtual ~ConcreateCreator();
protected:
virtual Product* FactoryMethod();
};
*******************************************
Factory.cpp janvyking999
******************************************
#include <iostream>
#include "Factory.h"
using namespace std;
ConcreateProduct::ConcreateProduct() {
cout<<"construction of ConcreateProduct"<<endl;
}
ConcreateProduct::~ConcreateProduct() {
cout<<"destruction of ConcreateProduct"<<endl;
}
void Creator::anOperation() {
Product* p = FactoryMethod();
cout<<"an operation of product"<<endl;
}
ConcreateCreator::ConcreateCreator() {
cout<<"construction of ConcreateCreator"<<endl;
}
ConcreateCreator::~ConcreateCreator() {
cout<<"destruction of ConcreateCreator"<<endl;
}
Product* ConcreateCreator::FactoryMethod() {
return new ConcreateProduct();
}
*******************************************
FactoryMain.cpp janvyking999
*******************************************
#include <cstdlib>
#include "Factory.h"
int main() {
Creator *p = new ConcreateCreator();
p->anOperation();
delete p;
system("pause");
return 0;
}
程序输出:
construction of ConcreateCreator
construction of ConcreateProduct
an operation of product
destruction of ConcreateCreator