抽象工厂模式(Abstract Factory Pattern)是围绕一个超级工厂创建其他工厂。该超级工厂又称其他工厂的工厂。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
意图
提供一个创建一系列相关或相互依赖对象的接口而不需指定他们具体的类。
如何解决
在一个产品族里面,定义多个产品
解决问题
解决接口选择的问题
优点
当一个产品族中的多个对象被设计成一起工作时,它能保证客户端始终只使用同一个产品族中的对象。
缺点
产品族扩展非常困难,增加一个系列的某一产品,既要在抽象的Creator里面加代码,又要在具体的里面增加代码。
注意事项
产品族难扩展,产品等级易扩展。
C++实现抽象工厂模式
实例:通过PC工厂和手机工厂和预装的操作系统产品来举例实现模式
//产品
class CLinux
{
public:
virtual ~CLinux();
virtual void Start() = 0; //产品的公共接口
};
class CLinuxMobile : public CLinux
{
public:
CLinuxMobile()
{
cout << "Create Linux Mobile" << endl;
}
virtual ~CLinuxMobile()
{}
virtual void Start()
{
cout << "Create Mobile Start" << endl;
}
};
class CLinuxPC : public CLinux
{
public:
CLinuxPC()
{
cout << "create linux PC." << endl;
}
virtual ~CLinuxPC() {};
virtual void Start()
{
cout << "linux PC start." << endl;
};
};
class CWindows
{
public:
virtual ~CWindows() {}
virtual void Start() = 0; //产品公共接口
};
class CWindowsMobile : public CWindows
{
public:
CWindowsMobile()
{
cout << "create windows mobile." << endl;
}
virtual ~CWindowsMobile() {};
virtual void Start()
{
cout << "windows mobile start." << endl;
};
};
class CWindowsPC : public CWindows
{
public:
CWindowsPC()
{
cout << "create windows PC." << endl;
}
virtual ~CWindowsPC() {};
virtual void Start()
{
cout << "windows PC start." << endl;
};
};
/工厂
class CFactory
{
public:
virtual ~CFactory(){};
//产品族有个产品组件
virtual CLinux* CreateLinux() = 0;
virtual CWindows* CreateWindows() = 0;
};
class CMobileFactory : public CFactory
{
public:
CMobileFactory()
{
cout << "create mobile factory." << endl;
}
virtual ~CMobileFactory(){};
virtual CLinux* CreateLinux()
{
return new CLinuxMobile;
};
virtual CWindows* CreateWindows()
{
return new CWindowsMobile;
};
};
class CPCFactory : public CFactory
{
public:
CPCFactory()
{
cout << "create PC factory." << endl;
}
virtual ~CPCFactory(){};
virtual CLinux* CreateLinux()
{
return new CLinuxPC;
};
virtual CWindows* CreateWindows()
{
return new CWindowsPC;
};
};
测试:
int main()
{
CFactory* pFactory = NULL;
//手机工厂。生产手机产品族,种类有Linux和Windows
pFactory = new CMobileFactory;
Test(pFactory);
delete pFactory;
cout << endl;
//PC工厂。生产PC产品族,种类有Linux和Windows
pFactory= new CPCFactory;
Test(pFactory);
delete pFactory;
system("pause");
return 0;
}
结果:
create mobile factory.
create linux mobile.
create windows mobile.
linux mobile start.
windows mobile start.
create PC factory.
create linux PC.
create windows PC.
linux PC start.
windows PC start.