意圖
提供一個創建一系列相關或相互依賴對象的接口,而無需指定它們具體的類。
場景
還是上次說的那個網絡游戲,定下來是一個休閒的FPS游戲。和CS差不多,8到16個玩家在游戲裡面分成2組對戰射擊。現在要實現初始化場景的工作。要呈現一個三維物體一般兩個元素是少不了的,一是這個物體的骨架,也就是模型,二就是這個骨架上填充的紋理。
我們知道,這樣的一個游戲不可能只有一張地圖,而且地圖的數量肯定是會一直增加的。如果游戲在初始化場景的時候需要根據不同的地圖分別加載模型和紋理對象,那麼勢必就會使得場景的擴充變得很不方便。由此,我們引入Abstract Factory,抽象工廠生產的都是實際類型的接口(或者抽象類型),如果加了新的場景可以確保不需要修改加載場景的那部分代碼。
示例代碼
using System;
using System.Reflection;
namespace AbstractFactoryExample
{
class Program
{
static void Main(string[] args)
{
Patrix patrix = new Patrix();
patrix.LoadScene("HalfPaper");
patrix.LoadScene("Matrix");
}
}
class Patrix
{
private PatrixSceneFactory GetGameScene(string gameSceneName)
{
return (PatrixSceneFactory)Assembly.Load("AbstractFactoryExample").CreateInstance("AbstractFactoryExample." + gameSceneName);
}
public void LoadScene(string gameSceneName)
{
PatrixSceneFactory psf = GetGameScene(gameSceneName);
Texture texture = psf.CreateTexture();
Model model = psf.CreateModel ();
model .FillTexture(texture);
}
}
abstract class PatrixSceneFactory
{
public abstract Model CreateModel ();
public abstract Texture CreateTexture();
}
abstract class Model
{
public abstract void FillTexture(Texture texture);
}
abstract class Texture
{
}
class HalfPaper : PatrixSceneFactory
{
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 : PatrixSceneFactory
{
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");
}
}
}