当前位置 博文首页 > KOOKNUT的博客:常见的设计模式(续)--C++基础

    KOOKNUT的博客:常见的设计模式(续)--C++基础

    作者:[db:作者] 时间:2021-07-02 21:31

    工厂方法模式(FACTORY METHOD):
    意图:定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method使一个类的实例化延迟到子类。
    动机:当我们用不同的工厂去生产不同的产品时候,我们不知道具体需要实例化的是哪一个工厂的对象,我们需要定义一个抽象工厂类来接受具体的工厂类指针,去完成我们的生产任务。
    思考:当一个产品抽象类旗下有不同的产品类型时,我们需要使用不同的工厂去分工完成生产任务。
    解决办法:定义一个工厂类,是一个抽象类,其具体实例化交由各个子工厂去执行,由子工场去完成生产任务。
    代码:

    class Product
    {
    public:
    	virtual void Show() = 0;
    };
    
    class Product1 : public Product
    {
    public:
    	void Show()
    	{
    		cout << "This is Product1" << endl;
    	}
    };
    
    class Product2 : public Product
    {
    public:
    	void Show()
    	{
    		cout << "This is Product2" << endl;
    	}
    };
    
    class Factory//抽象类
    {
    public:
    	virtual Product *CreateProduct() = 0;
    };
    
    class Factory1 : public Factory
    {
    public:
    	static Factory1* Instance();
    	Product *CreateProduct()
    	{
    		return new Product1();
    	}
    protected:
    	Factory1() {};
    private:
    	static Factory1* __Instance1;
    };
    Factory1* Factory1::__Instance1 = NULL;
    Factory1* Factory1::Instance()
    {
    	if (__Instance1 == NULL)
    	{
    		__Instance1 = new Factory1();
    	}
    	return __Instance1;
    }
    class Factory2 : public Factory
    {
    public:
    	static Factory2* Instance();
    	Product *CreateProduct()
    	{
    		return new Product2();
    	}
    protected:
    	Factory2() {};
    private:
    	static Factory2* __Instance2;
    };
    Factory2* Factory2::__Instance2 = NULL;
    Factory2* Factory2::Instance()
    {
    	if (__Instance2 == NULL)
    	{
    		__Instance2 = new Factory2();
    	}
    	return __Instance2;
    }
    int main(int argc, char *argv[])
    {
    	Factory *factory = Factory1::Instance();
    	Product* v1 =  factory->CreateProduct();
    	Factory *factory2 = Factory2::Instance();
    	Product* v2 = factory2->CreateProduct();
    
    	v1->Show();
    	v2->Show();
    
    	if (factory != NULL)
    	{
    		delete factory;
    		factory = NULL;
    	}
    	if (v1 != NULL)
    	{
    		delete v1;
    		v1 = NULL;
    	}
    	if (factory2 != NULL)
    	{
    		delete factory2;
    		factory2 = NULL;
    	}
    	if (v2 != NULL)
    	{
    		delete v2;
    		v2 = NULL;
    	}
    	system("pause");
    }
    

    “Everyone is always gonna go for the better everything.”
    参考资料:
    《设计模式》
    学习链接:
    https://blog.csdn.net/CoderAldrich/article/details/83114687

    cs
    下一篇:没有了