Abstract Factory定义:针对应用中具体使用一系列相关的类给定一个接口,由接口负责创建。
优点:
1. 分离了具体的类。
2. 使更换具体的工厂就可以实现产品的更换。
3. 有利于产品的一致性,因为抽象工厂创建的产品都符合统一的接口。
例如,有一个游戏,它有很多张地图,我们希望的当然是增加不同的地图时不需要改变加载地图的那部分代码,为此建一个抽象工厂:
abstract class GameSceneFactory
{
public abstract Model CreateModel();
public abstract Texture CreateTexture();
}
它包含2个抽象的实体,Model和Texture:
abstract class Model
{
public abstract void FillTexture(Texture texture);
}
abstract class Texture
{
}
下面是具体的地图场景,以及它们对应的具体的Model和Texture:
Code
class HalfPaper : GameSceneFactory
{
public override Model CreateModel()
{
return new HalfPaperModel();
}
public override Texture CreateTexture()
{
return new HalfPaperTexture();
}
}
class HalfPaperModel : Model
{
public HalfPaperModel()
{
Console.WriteLine("HalfPaper Model Created");
}
public override void FillTexture(Texture texture)
{
Console.WriteLine("HalfPaper Model is filled Texture");
}
}
class HalfPaperTexture : Texture
{
public HalfPaperTexture()
{
Console.WriteLine("HalfPaper Texture Created");
}
}
class Matrix : GameSceneFactory
{
public override Model CreateModel()
{
return new MatrixModel();
}
public override Texture CreateTexture()
{
return new MatrixTexture();
}
}
class MatrixModel : Model
{
public MatrixModel()
{
Console.WriteLine("Matrix Model Created");
}
public override void FillTexture(Texture texture)
{
Console.WriteLine("Matrix Model is filled Texture");
}
}
class MatrixTexture : Texture
{
public MatrixTexture()
{
Console.WriteLine("Matrix Texture Created");
}
} 然后再创建一个Game类提供对抽象工厂的访问:
Code
class Game
{
private GameSceneFactory GetGameScene(string gameSceneName)
{
return (GameSceneFactory)Assembly.Load("AbstractFactoryExample").CreateInstance("AbstractFactoryExample." + gameSceneName);
}
public void LoadScene(string gameSceneName)
{
GameSceneFactory psf = GetGameScene(gameSceneName);
Texture texture = psf.CreateTexture();
Model model = psf.CreateModel();
model.FillTexture(texture);
}
} 下面是使用这个抽象工厂的示例代码:
namespace AbstractFactoryExample
{
class Program
{
static void Main(string[] args)
{
Patrix patrix = new Patrix();
patrix.LoadScene("HalfPaper");
patrix.LoadScene("Matrix");
}
}
}