用户名: 密码: 验证码:           网站地图 高级搜索 RSS订阅 收藏本站
Google
您的位置:首页>>网络编程>>.Net编程>>阅读资讯:C#设计模式之四:Factory Method

C#设计模式之四:Factory Method

[ 来源: | 阅读:次 | 更新日期:2007-10-19 21:45:09 | 评论 0 条 | 我要投稿 ]
 本系列文章将向大家介绍一下C#的设计模式,此为第四篇文章,相信对大家会有所帮助的。废话不多说,继续来看。

  意图 www.yueluo.net

  定义一个创建产品对象的工厂接口,将实际创建工作推迟到子类中。

字串6

  场景

字串6

  上次,我们使用抽象工厂解决了生产一组产品的问题,但是我们把各个场景作为了具体工厂来生产场景模式和场景纹理两个产品。在调用代码中也并没有出现具体工厂的影子。其实,场景类要做的不仅仅是创建具体的产品系列,可能它还需要做一个初始化工作。那么,我们就需要在调用代码中能得到这个场景类。 字串7

  在前一节中,由于场景类(比如HalfPaper)本身是具体级别的(具体工厂)。那么,我们也不应该在调用代码中直接依赖场景类。因此,我们可以使用工厂方法来生产这个具体产品。

www.yueluo.net

  示例代码 字串9

  字串9

  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();
  }
  }

字串6


  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");
  }
  }
共2页: 上一页 1 [2] 下一页
Tags:C# 设计模式 Factory Method
责任编辑:
您的评论
用户名:新注册) 密码: 匿名评论 [所有评论]

·用户发表意见仅代表其个人意见,并且承担一切因发表内容引起的纠纷和责任
·本站管理人员有权在不通知用户的情况下删除不符合规定的评论信息或留做证据
·请客观的评价您所看到的资讯,提倡就事论事,杜绝漫骂和人身攻击等不文明行为