![]() |
|
引入 indirection
最后还需要做的是将选项从表挂接到 ContactPresentationModel
上以供查看。维基百科将计算机编程中的 indirection 定义为 “使用名称、引用或容器而不是值本身进行引用的能力”。通过绑定到稍后将填入的占位符上,可以将此方法与 ContactForm
和 ContactPresentationModel
结合使用。将其重构,以便 Contact
变量现在就替换 IObservable value
。根据成为 contactObservable
的需要更改变量和方法名称。更改后会导致出现一些编译错误。修正 enablementChangeListener
并用清单 22 中的代码进行测试。
清单 22. 将 TablePresentation 模型与 ContactPresentationModel 连接起来
if (!getEnableYearsMarried()) { Contact contact = (Contact) / getContactObservable().getValue(); if (contact != null) { contact.setYearsMarried(null); contact.setSpouse(null); } } . . . ContactPresentationModel presentationModel = new ContactPresentationModel( new WritableValue(Contact.class)); presentationModel.getContactObservable().setValue(contact); assertFalse(presentationModel.getEnableYearsMarried()); presentationModel.setEnableYearsMarried(true); contact.setSpouse("spouse"); contact.setYearsMarried("5"); presentationModel.setEnableYearsMarried(false); assertNull(contact.getSpouse()); assertNull(contact.getYearsMarried()); |
现在需要修正 ContactForm
。确保先前的 getContact()
方法已被重构为 getContactObservable()
。因为现在要绑定到 IObservableValue
而不是直接绑定到 Contact
对象,因此在绑定时必须更加明确这一点。修改 name
、spouse
和 yearsMarried
的 Property
对象构造函数以使第三个实参为 String.class
,第四个实参为 false。这样做将指定将要绑定到的属性的类型和它不是集合的事实。最后,通过将 ContactForm
构造函数更改为从 TablePresentationModel
获取 WritableValue
实例,来修正示例运行程序中的错误。
再次运行示例。注意表的第一个值已被选中并且显示在下面的表单中。如果更改 Name 字段的值,则表中该字段的值也将更改。更改表中的选项将更改表单中显示的对象。