实用模式:内部域特定语言
2010-09-30 22:42:30 来源:WEB开发网图 1 在 ScreenActionClass 上实现 DSL
public class ScreenObjectRegistry : IScreenObjectRegistry
{
private readonly List<ScreenAction> _actions =
new List<ScreenAction>();
private readonly IContainer _container;
private readonly ArrayList _explorerObjects = new ArrayList();
private readonly IApplicationShell _shell;
private readonly Window _window;
public IEnumerable<ScreenAction> Actions {
get { return _actions; } }
public IActionExpression Action(string name)
{
return new BindingExpression(name, this);
}
// Lots of other methods that are not shown here
}
要注册新屏幕,首先要调用上述 Action(name) 方法,然后返回作为 Expression Builder 的 BindingExpression 类的新实例,以配置新的 ScreenAction 对象,图 2 中显示了部分内容。
图 2 作为 Expression Builder 的 BindingExpression 类
public class BindingExpression : IBindingExpression, IActionExpression
{
private readonly ScreenObjectRegistry _registry;
private readonly ScreenAction _screenAction = new ScreenAction();
private KeyGesture _gesture;
public BindingExpression(string name, ScreenObjectRegistry registry)
{
_screenAction.Name = name;
_registry = registry;
}
public IBindingExpression Bind(Key key)
{
_gesture = new KeyGesture(key);
return this;
}
public IBindingExpression Bind(ModifierKeys modifiers, Key key)
{
_gesture = new KeyGesture(key, modifiers);
return this;
}
// registers an ICommand that will launch the dialog T
public ScreenAction ToDialog<T>()
{
return buildAction(() => _registry.CommandForDialog<T>());
}
// registers an ICommand that would open the screen T in the
// main tab area of the UI
public ScreenAction ToScreen<T>() where T : IScreen
{
return buildAction(() => _registry.CommandForScreen<T>());
}
public ScreenAction To(ICommand command)
{
return buildAction(() => command);
}
// Merely configures the underlying ScreenAction
private ScreenAction buildAction(Func<ICommand> value)
{
ICommand command = value();
_screenAction.Binding = new KeyBinding(command, _gesture);
_registry.register(_screenAction);
return _screenAction;
}
public BindingExpression Icon(Icon icon)
{
_screenAction.Icon = icon;
return this;
}
}
更多精彩
赞助商链接