编程语言
首页 > 编程语言> > C++设计模式——抽象工厂模式

C++设计模式——抽象工厂模式

作者:互联网

#include<iostream>
using namespace std;

//产品1
class Product1
{
	public:
		virtual void show()=0;
};
//产品2
class Product2
{
	public:
		virtual void show()=0;
}; 
//微软的产品1
class MicroProduct1 : public Product1
{
	public:
		void show()
		{
			cout<<"MicroProduct1\n";
		}
};
//微软的产品2
class MicroProduct2 : public Product2
{
	public:
		void show()
		{
			cout<<"MicroProduct2\n";
		}
};
//联想的产品1
class LenovoProduct1 : public Product1
{
	public:
		void show()
		{
			cout<<"LenovoProduct1\n";
		}
};
//联想的产品2
class LenovoProduct2 : public Product2
{
	public:
		void show()
		{
			cout<<"LenovoProduct2\n";
		}
};
//工厂
class Factory
{
	public:
		virtual Product1 * createProduct1()=0;
		virtual Product2 * createProduct2()=0;
};
//微软工厂
class MicroFactory : public Factory
{
	Product1 * createProduct1()
	{
		return new MicroProduct1();
	}
	Product2 * createProduct2()
	{
		return new MicroProduct2();
	}
};
//联想工厂
class LenovoFactory : public Factory
{
	Product1 * createProduct1()
	{
		return new LenovoProduct1();
	}
	Product2 * createProduct2()
	{
		return new LenovoProduct2();
	}
};
int main()
{
	Factory *micro = new MicroFactory();
    Product1 *p1 = micro->createProduct1();
    Product2 *p2 = micro->createProduct2();
    p1->show();
    p2->show();
    cout<<endl;

    Factory *lenovo = new LenovoFactory();
    Product1 *p3 = lenovo->createProduct1();
    Product2 *p4 = lenovo->createProduct2();
    p3->show();
    p4->show();
}

标签:show,void,C++,抽象,Product2,Product1,new,设计模式,public
来源: https://blog.csdn.net/qq_52553095/article/details/120463038