插件式设计开发⼼得(⼀)【⽂摘】
转⾃:
本⼈对插件式应⽤框架的开发是相当喜欢的,记得曾经写过⼀篇⽂章,《将⼯⼚模式升华为插件式框架》,这篇⽂章中写的是在控制台下实现的⼀种将⼯⼚模式进⼀步加⼯后的结果。这两天⼜重新理了⼀下思路,于是决定动⼿写⼀个winform环境下的插件式框架开发。当然,现在插件式开发的软件也是相当多的,这个可以⽹上搜⼀下,或者看我的《将⼯⼚模式升华为插件式框架》,最后有提到。
插件式开发的核⼼思想我想应该是针对接⼝编程,那么好吧,我们现在开始插件式框架开发之旅吧。我以尝试开发⼀个⼩型系统⼯具为例⼦,以此为基础进⾏介绍我的插件式开发的思想,希望⼤家多多交流。
插件式应⽤框架⼀般都有以下⼏部分组成:
1、宿主程序:主界⾯程序(包含各种⼯具、菜单等),插件引擎(解析插件程序集),通信契约。
2、插件
3、另外的程序集、组件库(起框架辅助作⽤)
好吧,现在我们开始设计我们⾃⼰的插件引擎吧。
⾸先,我们要新建⼀个IApplication接⼝,此接⼝包含了主界⾯程序中所包含的所有内容,⽐如菜单,⼯具栏,tabcontrol,tabpage等。IApplication接⼝是所有插件与主主界⾯程序通信的公共契约,所以⾮常重要。代码如下:
namespace WingOfDream.SystemTool.CoreFramework{
using System.Windows.Forms;
///宿主程序的所有属性
public interface IApplication{
///主程序标题
string Caption { get; set; }
///主程序当前使⽤的⼯具Tool名称
string CurrentTool { get; set; }
///主程序当前的ToolStrip容器
ToolStripContainer CurrentToolStripContainer { get; set; }
///当前的ToolStrip
ToolStrip CurrentToolStrip { get; set; }
///当前的菜单
MenuStrip CurrentMenuStrip { get; set; }
///主程序当前显⽰的TabControl
TabControl CurrentTabControl { get; set; }
///主程序当前显⽰的TabPage
TabPage CurrentTabPage { get; set; }
///主程序名称
string Name { get; }
/
//主程序窗体对象
Form MainPlatform { get; set; }
///主程序UI界⾯的Visible属性
bool Visible { get; set; }
}
}
读者可以看到,IApplication接⼝中包含的仅仅是⼀些属性,⽽插件就是通过这些属性,与主界⾯进⾏交互的。
下⾯来实现这个接⼝:
namespace WingOfDream.SystemTool.CoreFramework{
using System.Windows.Forms;
///实现IApplication
public class Application : IApplication{
///region IApplication 成员
public string Caption{
get{ return this.Caption; }
set{ this.Caption = value; }
}
public string CurrentTool{
get{ return this.CurrentTool; }
set{ this.CurrentTool = value; }
menustrip和toolstrip}
public ToolStripContainer CurrentToolStripContainer{
get{ return this.CurrentToolStripContainer; }
set{ this.CurrentToolStripContainer = value; }
}
public MenuStrip CurrentMenuStrip{
get{ return this.CurrentMenuStrip;}
set{ this.CurrentMenuStrip = value; }
}
public ToolStrip CurrentToolStrip{
get{ return this.CurrentToolStrip; }
set{ this.CurrentToolStrip = value; }
}
public TabControl CurrentTabControl{
get{ return this.CurrentTabControl; }
set{ this.CurrentTabControl = value; }
}
public TabPage CurrentTabPage{
get{ return this.CurrentTabPage; }
set{ this.CurrentTabPage = value; }
}
public string Name {
get { return this.Name; }
}
public Form MainPlatform{
get{ return this.MainPlatform; }
set{ this.MainPlatform = value; }
}
public bool Visible{
get{ return this.Visible; }
set{ this.Visible = value; }
}
}
}
要知道,接⼝⼀旦继承就必须实现。具体可以参看MSDN中关于接⼝跟抽象类的设计原则,或者《.NET设计规范》。
有了主的通信契约,我们就可以定义插件类型的接⼝了。
我们⾸先得定义⼀个IPlugin接⼝,该接⼝为所有插件的基接⼝,所有插件接⼝必须继承与该接⼝。代码如下:
namespace WingOfDream.SystemTool.CoreFramework{
///所有框架插件接⼝的基接⼝
public interface IPlugin  {
///按钮显⽰的⽂字
string Caption { get; }
///按钮所属类别
string Category { get; }
}
}
下⾯我们来设计插件接⼝,⾸先请看IApplication接⼝中声明的插件对象的UI对象。我们要开发的插件UI对象有命令(ICommand)按钮、菜单栏(IMenuDef)、⼯具(ITool),⼯具条(IToolBarDef)、还有tabpage(ITabPage)。