无废话C#设计模式之四:Factory Method
2009-04-02 08:21:31 来源:WEB开发网意图
定义一个创建产品对象的工厂接口,将实际创建工作推迟到子类中。
场景
上次,我们使用抽象工厂解决了生产一组产品的问题,但是我们把各个场景作为了具体工厂来生产场景模式和场景纹理两个产品。在调用代码中也并没有出现具体工厂的影子。其实,场景类要做的不仅仅是创建具体的产品系列,可能它还需要做一个初始化工作。那么,我们就需要在调用代码中能得到这个场景类。
在前一节中,由于场景类(比如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");
}
}
}
更多精彩
赞助商链接