意圖
定義一個創建產品對象的工廠接口,將實際創建工作推遲到子類中。
場景
上次,我們使用抽象工廠解決了生產一組產品的問題,但是我們把各個場景作為了具體工廠來生產場景模式和場景紋理兩個產品。在調用代碼中也並沒有出現具體工廠的影子。其實,場景類要做的不僅僅是創建具體的產品系列,可能它還需要做一個初始化工作。那麼,我們就需要在調用代碼中能得到這個場景類。
在前一節中,由於場景類(比如HalfPaper)本身是具體級別的(具體工廠)。那麼,我們也不應該在調用代碼中直接依賴場景類。因此,我們可以使用工廠方法來生產這個具體產品。
示例代碼
using System;
using System.Reflection;
namespace FactoryMethodExample
{
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("FactoryMethodExample").CreateInstance("FactoryMethodExample." + gameSceneName + "Factory");
}
public void LoadScene(string gameSceneName)
{
PatrixSceneFactory psf = GetGameScene(gameSceneName);
PatrixScene ps = psf.CreateScene();
ps.InitScene();
}
}
abstract class PatrixSceneFactory
{
public abstract PatrixScene CreateScene();
}
abstract class PatrixScene
{
public void InitScene()
{
Texture texture = CreateTexture();
Model model = CreateModel ();
model .FillTexture(texture);
}
public abstract Model CreateModel ();
public abstract Texture CreateTexture();
}
abstract class Model
{
public abstract void FillTexture(Texture texture);
}
abstract class Texture
{
}
class HalfPaperFactory : PatrixSceneFactory
{
public override PatrixScene CreateScene()
{
return new HalfPaper();
}
}
class HalfPaper : PatrixScene
{
public HalfPaper()
{
Console.WriteLine("HalfPaper Creating");
}
public override Model CreateModel ()
{
return new HalfPaperModel ();
}
public override Texture CreateTexture()
{
return new HalfPaperTexture();
}
}
class HalfPaperModel : Model
{
public HalfPaperModel ()
{
Console.WriteLine("HalfPaper Model Creating");
}
public override void FillTexture(Texture texture)
{
Console.WriteLine("HalfPaper Model is filled Texture");
}
}
class HalfPaperTexture : Texture
{
public HalfPaperTexture()
{
Console.WriteLine("HalfPaper Texture Created");
}
}
class MatrixFactory : PatrixSceneFactory
{
public override PatrixScene CreateScene()
{
return new Matrix();
}
}
class Matrix : PatrixScene
{
public Matrix()
{
Console.WriteLine("Matrix Created");
}
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");
}
}
}