工厂环境描述,工厂模式{C#描述}

概述
    在软件系统中,经常面临着“一系列相互依赖的对象”的创建工作;同时由于需求的变化,往往存在着更多系列对象的创建工作。如何应对这种变化?如何绕过常规的对象的创建方法(new),提供一种“封装机制”来避免客户程序和这种“多系列具体对象创建工作”的紧耦合?这就是我们要说的抽象工厂模式。
    简而言之: 通过传入"类名", 创建不同的对象.
意图
    提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
类: CAdmin(管理员类), CUser(普通用户类)
接口: IUser(用户类)
关系: CAdmin(管理员类), CUser(用户类) 都实现 IUser接口
类: CAdmin(管理员类)
namespace WebApplication1 { public class CAdmin:IUser { #region IUser 成员 public string GetName() { return "我是管理员, 小样敢乱发言逮捕!"; } #endregion } }
类: CUser(普通用户类)
namespace WebApplication1 { public class CUser:IUser { #region IUser 成员 public string GetName() { return "我是普通用户!"; } #endregion } }
接口: IUser(用户类)
namespace WebApplication1 { interface IUser { string GetName(); } }
 
调用(实现部分):
//用户对象 protected void Button1_Click(object sender, EventArgs e) { Label1.Text = GetName("WebApplication1.CUser"); } //管理员对象 protected void Button2_Click(object sender, EventArgs e) { Label2.Text = GetName("WebApplication1.CAdmin"); } //得到名字, 当然还有简短的话 - - public string GetName(string className) { IUser user = (IUser)Assembly.Load("WebApplication1").CreateInstance(className); return user.GetName(); }
源码下载
Tags:  简单工厂模式 java工厂模式 抽象工厂模式 工厂模式 工厂环境描述

延伸阅读

最新评论

发表评论