Tob*_*obi 5 java oop design-patterns
我想知道下面的模式是什么,如果它有一个名字.
目的
存储与object(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
}
Run Code Online (Sandbox Code Playgroud)
与子类化相比,优点是不需要工厂MyObject,只需使实现者MyApi可以将额外数据与对象相关联.
与实现者中的a相比WeakHashMap,缺点是MyObject对客户端无用的两种方法,但优点是简单性.
这种模式的一个很好的属性是你可以通过改变字段来概括它来为每个节点存储任意数量的不同类型的附件Map<Class<?>, Attachment> attachments,而根本不能用子类来完成.
我已经看到使用通用形式成功地在树重写系统中注释树节点,其中各种数据由处理节点的各种模块使用.(cf指向父节点的指针,原始信息)
题
这个模式有名字吗?如果是这样,它是什么?任何参考?