Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5615
  • 博文数量: 4
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 61
  • 用 户 组: 普通用户
  • 注册时间: 2013-11-27 14:01
文章分类
文章存档

2014年(1)

2013年(3)

我的朋友
最近访客

分类: C#/.net

2013-12-22 14:37:02

  适配器WxTOFormsAdapter可以工作但是很粗糙,因为wx.NET文本控件不是System.Windows.Forms.Textbox。更好的方法是考虑手中的任务,然后定义一个接口作为Adapter模式的基础。选择的方法需要考虑作为数据源和接收器的各种控件。适配器接口需要提取数据以及为数据赋值的方法。适配器接口定义如下:

public interface IControlAdapter {

returntype GetValue(ControlType control) where returntype: class; void SetValue(ControlType control, type value);

}

  IControlAdapter.GetValue 方法用于获取数值,IControlAdapter. SetValue 方法则用于赋值。IControlAdapter接口的定义没有使用泛型,但方法使用了。这样做的目的是为了支持所有类型的GUI控件元素。接口必须能够支持任何控件类型,让IControlAdapter接口指定类型是没有用处的。当在接口层次使用泛型参数时,对接口的特例化将导致只支持单一类型。这意味着如果IControlAdapter被特例化成TextBox,则所有的方法都必须转换成TextBox类型。

  方法没有那些限制,通过TranslationSenrices.DoTranslation的方法实现可以看到:

public void DoTranslation(Controll src, Control2 dest) { _adapter.SetValue(dest,

_translation.Translate(_adapter.GetValue(src)));

}

  变量_adapter是IControlAdapter的接口实例。方法GetValue获取控件的值,然后使用SetValue对控件赋值。在方法层次上使用泛型参数使得可以使用任何数据类型。当然,当在方法层次上不受限制地使用泛型时,就必须得使用类型转换。不明白的请看相关知识:

  下面是为System.Windows.Forms命名空间的IControlAdapter实现:

private class WindowsAdapter: Abstractions.IControlAdapter {

public type GetValue(ControlType control) where type: class { if(control is TextBox) {

TextBox cls = control as TextBox; return cls.Text as type;

}

return default(type);

}

public void SetValue(ControlType control, type value) { if(control is TextBox) {

TextBox cls = control as TextBox;

String strValue = value as String; cls.Text = strValue;

}

}

}

  在方法GetValue和SetValue的实现中,注意是如何使用is和as声明来进行动态类型转换和类型检查的。使用动态转型和动态检查使适配器实现能够检查传递的是哪种类型的控件,然后执行合适的操作。例如,对于TexBox的GetValue方法,意思是获取文本内容。如果控件是复选框,就意味着获取选中或者未选中值。相同的规则也适用于SetValue方法。

  如果需要实现不同的工具包,适配器的价值就更明显了。在那种情况下,唯一需要的就是实现一个新的IControlAdapter,正如下面wx.NET例子中演示的一样:

private class wxAdapter: Abstractions.IControlAdapter {

public type GetValue(ControlType control) where type: class {
if(control is TextCtrl) { TextCtrl cls = control as return cls.Value as type;

}

return default(type);

}
TextCtrl;
type>(ControlType control, type value) { TextCtrl;
public void SetValue
TextCtrl cls = control as String strValue = value as String; cls.Value = strValue;

}

}

}

  这一次GetValue和SetValue方法检查输入控件是否为wx.NET控件。而TranslationServices类并不关心使用哪个适配器,它只执行需要它完成的任务。
阅读(164) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~