[英]What's this java pattern called?
我想知道下面的模式是什么,如果它有一个名字。
目的
存储与对象( MyObject
)关联的数据,但该数据对于处理该对象的接口的实现是私有的。 对象的客户端没有业务查看此数据。
备择方案
一些替代方案是
WeakHashMap<MyObject, FooApiMyObjectAttachment>
在接口的实现中维护, MyObject
和子类。 代码示例
public interface MyApi {
void doSomething(MyObject x);
}
public class MyObject {
public interface Attachment {} // empty interface, type bound only
private Attachment attachment;
public void setAttachment(Attachment attachment) {
this.attachment = attachment;
}
public <T extends Attachment> T getAttachment(Class<T> type) {
return type.cast(attachment);
}
}
class FooApiMyObjectAttachment implements MyObject.Attachment {
Foo foo; // some data that one MyApi implementer `foo' wants to persist between calls, but that is neither needed nor desired on MyObject
}
class BarApiMyObjectAttachment implements MyObject.Attachment {
Bar bar; // some data that another MyApi implementer `bar' wants to persist between calls, but that is neither needed nor desired on MyObject
}
class FooApi implements MyApi {
// associates FooApiMyObjectAttachment with any MyObjects passed to it or created by it
}
class BarApi implements MyApi {
// associates BarApiMyObjectAttachment with any MyObjects passed to it or created by it
}
与子类化相比,优点是MyObject
不需要工厂,只是为了使MyApi
实现者能够将额外的数据与对象相关联。
与实现者中的WeakHashMap
相比,缺点是MyObject
上的两个对客户端无用的方法,但优点是简单。
这种模式的一个很好的属性是你可以通过将字段更改为Map<Class<?>, Attachment> attachments
来概括它,以便为每个节点存储任意数量的不同类型的Map<Class<?>, Attachment> attachments
,这完全不能通过子类化完成。
我已经看到使用通用形式成功地在树重写系统中注释树节点,其中各种数据由处理节点的各种模块使用。 (cf指向父节点的指针,原始信息)
题
这个模式有名字吗? 如果是这样,它是什么? 任何参考?
它看起来像一个结构模式,非常接近于整体部分或复合材料。
在线查找参考资料,全部内容概述:
有时称为复合
帮助组合(部分)的聚合,它们一起形成语义单元(整体)。
无法直接访问部件
将对象组合成树结构以表示部分整体层次结构。 Whole-Part允许客户统一处理单个对象和对象的组合
实际上你正在做的事情和复合材料之间的区别在于你存储的是非复合材料,所以你没有得到复合材料允许的树形结构,但是UML看起来就像没有猪耳朵一样。
找到了!
可以使用多个附件的形式( Map<Class<?>, Attachment> attachments
)由Erich Gamma描述为扩展对象模式 。
四人帮称这是纪念品 。
角色对象模式真的非常相似,甚至可以说我得出的结论是我自己的问题的答案是: 它是角色对象模式 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.