实现
# include <iostream>
# include <memory>
class Product {
public:
virtual ~ Product ( ) { }
virtual void Operation ( ) const = 0 ;
} ;
class ConcreteProductA : public Product {
public:
virtual void Operation ( ) const override {
std:: cout << "Product A" << std:: endl;
}
} ;
class ConcreteProductB : public Product {
public:
virtual void Operation ( ) const override {
std:: cout << "Product B" << std:: endl;
}
} ;
enum class ProductType: uint8_t {
ProductA = 0 ,
ProductB = 1
} ;
class Factory {
public:
Product * CreateProduct ( enum ProductType type) const {
switch ( type) {
case ProductType:: ProductA:
return new ConcreteProductA;
case ProductType:: ProductB:
return new ConcreteProductB;
default :
throw std:: invalid_argument ( "Invalid product type" ) ;
}
}
} ;
int main ( int argc, char * * argv)
{
Factory factory;
ConcreteProductA * productA = reinterpret_cast< ConcreteProductA* > ( factory. CreateProduct ( ProductType:: ProductA) ) ;
productA-> Operation ( ) ;
delete productA;
ConcreteProductB* productB = reinterpret_cast< ConcreteProductB* > ( factory. CreateProduct ( ProductType:: ProductB) ) ;
productB-> Operation ( ) ;
delete productB;
return 0 ;
}
# include <iostream>
# include <memory>
class Product {
public:
virtual ~ Product ( ) { }
virtual void Operation ( ) const = 0 ;
} ;
class ConcreteProductA : public Product {
public:
virtual void Operation ( ) const override {
std:: cout << "Product A" << std:: endl;
}
} ;
class ConcreteProductB : public Product {
public:
virtual void Operation ( ) const override {
std:: cout << "Product B" << std:: endl;
}
} ;
class Factory {
public:
virtual ~ Factory ( ) { }
virtual Product * CreateProduct ( ) = 0 ;
} ;
class ProductAFactory: public Factory {
public:
virtual Product * CreateProduct ( ) override {
return new ConcreteProductA ( ) ;
}
} ;
class ProductBFactory: public Factory {
public:
virtual Product * CreateProduct ( ) override {
return new ConcreteProductB ( ) ;
}
} ;
int main ( int argc, char * * argv)
{
Factory * a_factory = new ProductAFactory ( ) ;
Factory * b_factory = new ProductBFactory ( ) ;
auto a_product = a_factory-> CreateProduct ( ) ;
auto b_product = b_factory-> CreateProduct ( ) ;
a_product-> Operation ( ) ;
b_product-> Operation ( ) ;
delete a_product;
delete b_product;
delete a_factory;
delete b_factory;
return 0 ;
}