您所在的位置:开发 > 架构&设计 > 在C#程序中实现插件架构(2)

在C#程序中实现插件架构(2)

2006-02-20 16:15 电子科技大学 夏桅 译 blog.sunmast.com/sunmast 我要评论(0) 字号:T | T
一键收藏,随时查看,分享好友!

这篇文章将讲述如何利用C#奇妙的特性,实现插件架构,用插件(plug-ins)机制建立可扩展的解决方案。

AD:

源代码
示例程序的完整的源代码可以在这里下载:http://www.sunmast.com/code/PlugSample.zip

译者注:以前就考虑过在.NET里面如何实现插件机制,做来做去总是觉得设计上不够好.而昨天在网上无意中发现了这篇文章,写的实在是太棒了,所以看完之后,决定把它翻译过来,前后一共花了大概10个小时吧.翻译的可能不太好,请见谅.文中有什么错误,请不吝指正.

备注
1 Erich Gamma et al. Design Patterns (Addison-Wesley, 1995).

图片一:

列表一:The IPlug interface

public interface IPlug
{
IPlugData GetData();
PlugDataEditControl GetEditControl(IPlugData Data);
bool Save(string Path);
bool Print(PrintDocument Document);
}

列表二:The PlugDisplayNameAttribute class definition

AttributeUsage(AttributeTargets.Class)
public class PlugDisplayNameAttribute : System.Attribute
{
private string _displayName;

public PlugDisplayNameAttribute(string DisplayName) : base()
{
_displayName=DisplayName;
return;
}

public override string ToString()
{
return _displayName;
}

列表三:A partial listing of the EmployeePlug class definition

PlugDisplayName("Employees")
PlugDescription("This plug is for managing employee data")
public class EmployeePlug : System.Object, IPlug
{
public IPlugData GetData()
{
IPlugData data = new EmployeeData
{
new EmployeeData("Jerry", "Seinfeld")
,new EmployeeData("Bill", "Cosby")
,new EmployeeData("Martin", "Lawrence")
};

return data;
}

public PlugDataEditControl GetEditControl(IPlugData Data)
{
return new EmployeeControl((EmployeeData)Data);
}

public bool Save(string Path)
{
//implementation not shown
}

public bool Print(PrintDocument Document)
{
//implementation not shown
}
}

列表四:The method LoadPlugs

private void LoadPlugs()
{
string files = Directory.GetFiles("Plugs", "*.plug");

foreach(string f in files)
{

try
{
Assembly a = Assembly.LoadFrom(f);
System.Type types = a.GetTypes();
foreach(System.Type type in types)
{
if(type.GetInterface("IPlug")!=null)
{
if(type.GetCustomAttributes(typeof(PlugDisplayNameAttribute),
false).Length!=1)
throw new PlugNotValidException(type,
"PlugDisplayNameAttribute is not supported");
if(type.GetCustomAttributes(typeof(PlugDescriptionAttribute),
false).Length!=1)
throw new PlugNotValidException(type,
"PlugDescriptionAttribute is not supported");

_tree.Nodes.Add(new PlugTreeNode(type));
}
}
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
}

return;
}

关于作者
Shawn Patrick Walcheske是美国Arizona州Phoenix市的一名软件开发工程师.他同时是Microsoft Certified Solution Developer和Sun Certified Programmer for the Java 2 Platform.你可以在这里联系到他, questions@walcheske.com.

原文作者:Shawn Patrick Walcheske

原文链接:http://www.cuj.com/documents/s=8209/cujweb0301walcheske/

(责任编辑:铭铭)

内容导航

分享到:

网友评论TOP5

查看所有评论(

提交评论

  1. 专题:JVM编程语言,你的选择?
  2. 宅男程序员给老婆课程之11:域模型

文章排行

本月本周24小时

热点专题

更多>>

读书

Linux安全体系分析与编程
本书选择经典的开放源代码,全面系统地分析了Linux安全机制。本书共有17章,前10章着重介绍了Linux操作系统的安全机制及实现方法

51CTO旗下网站

领先的IT技术网站 51CTO 领先的中文存储媒体 WatchStor 中国首个CIO网站 CIOage 中国首家数字医疗网站 HC3i 移动互联网生活门户 灵客风LinkPhone