实现
# include <iostream>
# include <memory>
class Product {
public:
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 ;
}