一、定义
提供一个创建一系列相关或相互依赖的接口,而无需指定他们具体的类。
二、分析
1、模式关键词
- 创建一系列相关对象,延迟到具体的工程类来确定实际创建的对象
2、优点
- 分离了具体的类,使用时用抽象工厂类来创建对象。
- 易于交换产品系列。
- 有利于产品一致性,才用的是同系列的对象。
3、缺点
- 难以支撑新种类的产品,新加一种产品需要修改所有工厂类。
三、实践
#pragma once
#include <string>
#include <vector>
#include <iostream>
using namespace std;
class AbstractScene
{
private:
long long _instanceId;
public:
AbstractScene(long long instanceId)
{
_instanceId = instanceId;
}
long long get_instanceId()
{
return _instanceId;
}
};
class AbstractEntity
{
private:
long long _instanceId;
public:
AbstractEntity(long long instanceId)
{
_instanceId = instanceId;
}
long long get_instanceId()
{
return _instanceId;
}
};
class ServerEntity : public AbstractEntity
{
public:
ServerEntity(long long id) : AbstractEntity(id)
{
cout << "create server entity" << endl;
}
};
class ServerScene: public AbstractScene
{
public:
ServerScene(long long id):AbstractScene(id)
{
cout << "create server scene" << endl;
}
};
class ClientEntity : public AbstractEntity
{
public:
ClientEntity(long long id) :AbstractEntity(id)
{
cout << "create client entity" << endl;
}
};
class ClientScene : public AbstractScene
{
public:
ClientScene(long long id) :AbstractScene(id)
{
cout << "create client scene" << endl;
}
};
class AbstractSceneFactory
{
public:
virtual AbstractScene* CreateScene(long long instanceId)
{
return nullptr;
}
virtual AbstractEntity* CreateEntity(long long instanceId)
{
return nullptr;
}
};
class ServerSceneFactory : public AbstractSceneFactory
{
public:
virtual AbstractScene* CreateScene(long long instanceId)
{
return new ServerScene(instanceId);
}
virtual AbstractEntity* CreateEntity(long long instanceId)
{
return new ServerEntity(instanceId);
}
};
class ClientSceneFactory : public AbstractSceneFactory
{
public:
virtual AbstractScene* CreateScene(long long instanceId)
{
return new ClientScene(instanceId);
}
virtual AbstractEntity* CreateEntity(long long instanceId)
{
return new ClientEntity(instanceId);
}
};
class AbstractFactoryTest
{
public:
void DoTest()
{
CreateAll(new ServerSceneFactory());
CreateAll(new ClientSceneFactory());
}
void CreateAll(AbstractSceneFactory* factory)
{
factory->CreateScene(1);
factory->CreateEntity(2);
}
};