产品及其子类实现

以手机加工厂开展例子

  1. class Phone {
  2. public:
  3. virtual void Operation() = 0;
  4. }
  5. class Xiaomi : public Phone {
  6. public:
  7. void Operation() override {
  8. printf("为发热而生!");
  9. }
  10. }
  11. class Huawei : public Phone {
  12. public:
  13. void Operation() override {
  14. printf("不买不是中国人!");
  15. }
  16. }
  17. class Apple : public Phone {
  18. public:
  19. void Operation() override {
  20. printf("傲视群雄!");
  21. }
  22. }

工厂方法的不同实现

简单工厂(一般用于初期实现)

生成的逻辑一般位于工厂之中【if…else等】,不符合开放封闭原则

代码示例 - 图1

  1. class PhoneFactory{
  2. public:
  3. static Phone* createPhone(std::string Type){
  4. if(Type=="小米"){
  5. return new Xiaomi();
  6. }else if (Type == "华为"){
  7. return new Huawei();
  8. }else if (Type == "苹果"){
  9. return new Apple();
  10. }else{
  11. return NULL;
  12. }
  13. }
  14. }

工厂方法(为每个产品子类创建一个子工厂)

符合开放封闭及单一职责

代码示例 - 图2

  1. class PhoneFactory {
  2. public:
  3. virtual ~PhoneFactory(){}
  4. virtual Product* FactoryMethod() const =0;
  5. void SomeOperation() const {
  6. Phone* phone=FactoryMethod();
  7. phone->Operation();
  8. delete product;
  9. }
  10. }
  11. /*Concrete Creator override factory method to supply different Product Class*/
  12. class XiaomiFactory: public PhoneFactory{
  13. public:
  14. Product* FactoryMethod() const override {
  15. return new Xiaomi();
  16. }
  17. }
  18. class HuaweiFactory: public PhoneFactory{
  19. public:
  20. Product* FactoryMethod() const override {
  21. return new Huawei();
  22. }
  23. }
  24. class AppleFactory: public PhoneFactory{
  25. public:
  26. Product* FactoryMethod() const override {
  27. return new Apple();
  28. }
  29. }

抽象工厂(与上述两种方法无关)

主要整合多个不同的对象!

代码示例 - 图3
代码示例 - 图4

PC类

  1. class PC{
  2. public
  3. virtual void Operation() = 0 ;
  4. }
  5. class MiPC: public PC {
  6. public:
  7. void Operation() override {
  8. printf("制造小米电脑");
  9. }
  10. }
  11. class MAC: public PC {
  12. public:
  13. void Operation() override {
  14. printf("制造苹果电脑");
  15. }
  16. }

抽象工厂

  1. class MultiFactory{
  2. public:
  3. Phone* phoneCreator() const =0 ;
  4. PC* pcCreator() const = 0;
  5. }
  6. class XiaomiFactory : public MultiFactory{
  7. public:
  8. Phone* phoneCreator() const override {
  9. return new Xiaomi();
  10. }
  11. PC* pcCreator() const override {
  12. return new MiPC();
  13. }
  14. }
  15. class AppleFactory : public MultiFactory{
  16. public:
  17. Phone* phoneCreator() const override {
  18. return new Apple();
  19. }
  20. PC* pcCreator() const override {
  21. return new MAC();
  22. }
  23. }