汇总成员的介绍 [英] Presentation of an Aggregate Member
问题描述
如何出于展示的目的公开聚合成员,同时防止该成员直接被修改?因此,为了在UI上显示该成员,我需要对该成员进行只读访问,例如:
How do you expose an aggregate member for the purpose of presentation, while at the same time preventing that member from getting modified directly? So, I need something like read-only access to that member for the purpose of showing it on UI, For example:
class A {
B b;
void doSomething() {
b.update();
}
}
class B {
String getTitle() {
return title;
}
Items getItems() {
return items;
}
void update() {
...
}
}
interface SomeView {
void show(Items items);
}
一种快捷方法是添加方法A::getB()
并调用someView.show(b.getItems())
,但是随后返回的B
实例可以在A
之外进行修改(B::update()
可以在A
).
The quick-and-dirty solution would be to add a method A::getB()
and call someView.show(b.getItems())
but then the returned B
instance could be modified outside of A
(the B::update()
could be called outside A
).
我正在考虑几种解决方案,但是不确定哪种方案最好,或者是否已经有一种普遍的做法.
I am thinking of several solutions but not quite sure which are best or if there is already a common practice to do so.
我想到的解决方案之一是拥有B
的只读版本,该版本由A
返回.
One of the solution that I have in mind is having a read-only version of B
that is returned by A
.
class A {
ReadOnlyB getReadOnlyB() {
return new ReadOnlyB(b);
}
}
class ReadOnlyB {
B b;
ReadOnlyB(B b) {
this.b = b;
}
String getTitle() {
return b.getTitle();
}
Items getItems() {
return b.getItems();
}
}
推荐答案
您可以对B
使用只读接口.在内部,在A
类中,您使用类B
,但是在外部(对于客户端),您提供了B
只读接口.这是一个示例:
You could use read-only interfaces for B
. Internally, in A
class, you use the class B
but to the outside (to the clients) you give a read-only interface of B
. Here is a sample:
class A
{
private B b;
void doSomething() {
//internally you use this.b
b.update();
}
//please name this method according to its purpose
ReadOnlyB getB()
{
return b;
}
}
class B implements ReadOnlyB
{
String getTitle() {
return title;
}
Items getItems() {
return items;
}
void update() {
...
}
}
//please name this interface according to its purpose!
interface ReadOnlyB
{
Items getItems();
}
interface SomeView
{
void show(Items items);
}
但是,这会破坏迪米特法律.最好从A
返回Items
,如下所示:
However, this would break the Law of Demeter. It would be better to return the Items
from A
, like this:
class A
{
private B b;
void doSomething() {
b.update();
}
Items getItems()
{
return b.getItems();
}
}
这篇关于汇总成员的介绍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!