zoukankan      html  css  js  c++  java
  • 【设计模式】工厂模式

    工厂模式解决具有一系列相同属性、方法的类的创建问题。

    首先将具有相同属性、方法的类ConcreteProduct抽象出基类Product。

    为每个Product创建一个工厂类ConcreteFactory,工厂类又抽象出基类Factory,基类Factory中定义纯虚函数ConcreteFactory。

    C++代码实现:

    Product.h

    #ifndef _Product_H_
    #define _Product_H_
    #include <iostream>
    
    class Product
    {
    public:
        Product(){}
        virtual ~Product(){}
        virtual void Do() = 0;
    protected:
    private:
    };
    
    
    class ConcreteProduct1 : public Product
    {
    public:
        ConcreteProduct1(){}
        virtual ~ConcreteProduct1(){}
        virtual void Do();
    protected:
    private:
    };
    
    
    class ConcreteProduct2 : public Product
    {
    public:
        ConcreteProduct2(){}
        virtual ~ConcreteProduct2(){}
        virtual void Do();
    protected:
    private:
    };
    
    #endif
    View Code

    Product.cpp

    #include "Product.h"
    
    void ConcreteProduct1::Do()
    {
        std::cout << "Product1 Do!" << std::endl;
    }
    
    void ConcreteProduct2::Do()
    {
        std::cout << "Product2 Do!" << std::endl;
    }
    View Code

    Factory.h

    #ifndef _FACTORY_H_
    #define _FACTORY_H_
    #include "Product.h"
    
    class Factory
    {
    public:
        Factory(){}
        virtual ~Factory(){}
        virtual Product* CreateProduct() = 0;
    protected:
    private:
    };
    
    class ConcreteFactory1 : public Factory
    {
    public:
        ConcreteFactory1(){}
        virtual ~ConcreteFactory1(){}
        virtual Product* CreateProduct();
    protected:
    private:
    };
    
    class ConcreteFactory2 : public Factory
    {
    public:
        ConcreteFactory2(){}
        virtual ~ConcreteFactory2(){}
        virtual Product* CreateProduct();
    protected:
    private:
    };
    
    #endif
    View Code

    Factory.cpp

    #include "Factory.h"
    
    Product* ConcreteFactory1::CreateProduct()
    {
        return new ConcreteProduct1();
    }
    
    Product* ConcreteFactory2::CreateProduct()
    {
        return new ConcreteProduct2();
    }
    View Code

    main.cpp

    #include "Factory.h"
    #include "Factory.h"
    
    class Test
    {
    public:
        Test(){}
        ~Test(){}
        void DoTest(Factory* f)
        {
            Product* p = f->CreateProduct();
            p->Do();
        }
    protected:
    private:
    };
    
    int main(int argc,char* argv[])
    {
        Test* t = new Test();
        Factory* f1 = new ConcreteFactory1();
        t->DoTest(f1);
    
        Factory* f2 = new ConcreteFactory2();
        t->DoTest(f2);
        return 0;
    }
    View Code
  • 相关阅读:
    ORACLE数据库备份与恢复详解
    Oracle块,区,段
    Oracle触发器
    SQL
    Oracle 用户管理权限
    Mybatis_One
    面向对象编程应用实例
    面向对象之方法2
    面向对象之方法1
    面向对象之结构体2
  • 原文地址:https://www.cnblogs.com/TonyZhao/p/3469766.html
Copyright © 2011-2022 走看看