main.cpp
#include "AbstractFactory.h" #include "Product.h" #include <iostream> using namespace std; int main(int argc, char *argv[]) { AbstractFactory *cf1 = new ConcreateFactory1(); cf1->CreateProductA(); cf1->CreateProductB(); AbstractFactory *cf2 = new ConcreateFactory2(); cf2->CreateProductA(); cf2->CreateProductB(); return 0; }
Product.h
#ifndef _PRODUCT_H #define _PRODUCT_H class AbstractProductA { public : virtual ~AbstractProductA(); protected : AbstractProductA(); }; class AbstractProductB { public: virtual ~AbstractProductB(); protected: AbstractProductB(); }; class ProductA1 :public AbstractProductA { public : ProductA1(); ~ProductA1(); }; class ProductA2 :public AbstractProductA { public: ProductA2(); ~ProductA2(); }; class ProductB1 :public AbstractProductB { public: ProductB1(); ~ProductB1(); }; class ProductB2 :public AbstractProductB { public: ProductB2(); ~ProductB2(); }; #endif
Product.cpp
#include "Product.h" #include <iostream> using namespace std; AbstractProductA::AbstractProductA() {} AbstractProductA::~AbstractProductA() {} AbstractProductB::AbstractProductB() {} AbstractProductB::~AbstractProductB() {} ProductA1::ProductA1() { cout << "ProductA1..." << endl; } ProductA1::~ProductA1() {} ProductA2::ProductA2() { cout << "ProductA2..." << endl; } ProductA2::~ProductA2() {} ProductB1::ProductB1() { cout << "ProductB1..." << endl; } ProductB1::~ProductB1() {} ProductB2::ProductB2() { cout << "ProductB2..." << endl; } ProductB2::~ProductB2() {}
AbstractFactory.h
#ifndef _ABSTRACT_FACTORY_H #define _ABSTRACT_FACTORY_H class AbstractProductA; class AbstractProductB; class AbstractFactory { public : virtual ~AbstractFactory(); virtual AbstractProductA *CreateProductA() = 0; virtual AbstractProductB *CreateProductB() = 0; protected : AbstractFactory(); }; class ConcreateFactory1 : public AbstractFactory { public : ConcreateFactory1(); ~ConcreateFactory1(); AbstractProductA *CreateProductA(); AbstractProductB *CreateProductB(); }; class ConcreateFactory2 : public AbstractFactory { public: ConcreateFactory2(); ~ConcreateFactory2(); AbstractProductA *CreateProductA(); AbstractProductB *CreateProductB(); }; #endif
AbstractFactory.cpp
#include "AbstractFactory.h" #include "Product.h" #include <iostream> using namespace std; AbstractFactory::AbstractFactory() {} AbstractFactory::~AbstractFactory() {} ConcreateFactory1::ConcreateFactory1() {} ConcreateFactory1::~ConcreateFactory1() {} AbstractProductA *ConcreateFactory1::CreateProductA() { return new ProductA1(); } AbstractProductB *ConcreateFactory1::CreateProductB() { return new ProductB1(); } ConcreateFactory2::ConcreateFactory2() {} ConcreateFactory2::~ConcreateFactory2() {} AbstractProductA *ConcreateFactory2::CreateProductA() { return new ProductA1(); } AbstractProductB *ConcreateFactory2::CreateProductB() { return new ProductB1(); }
时间: 2024-11-05 19:41:22