源代码示例程序的完整的源代码可以在这里下载:
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/
(责任编辑:
铭铭)
(0票)
(0票)
(0票)
(0票)
(0票)
(0票)