繁体   English   中英

这个java模式叫什么?

[英]What's this java pattern called?

我想知道下面的模式是什么,如果它有一个名字。

目的

存储与对象( MyObject )关联的数据,但该数据对于处理该对象的接口的实现是私有的。 对象的客户端没有业务查看此数据。

备择方案

一些替代方案是

  1. 一个WeakHashMap<MyObject, FooApiMyObjectAttachment>在接口的实现中维护,
  2. 使用子类化和工厂到处创建值,以便额外的数据可以存储在子类或
  3. 使用子类并接受API中的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描述为扩展对象模式

四人帮称这是纪念品

角色对象模式真的非常相似,甚至可以说我得出的结论是我自己的问题的答案是: 它是角色对象模式

这是什么 %<div id="text_translate"><p> 我最近遇到了以下字符串:“%<s”。 我注意到这具有以下效果:</p><pre> String sampleString = "%s, %<s %<s"; String output = String.format(sampleString, "A"); System.out.println(output); // A, A A.</pre><p> 我试图用谷歌搜索这个 %<s 叫什么,但无济于事。 我从上面的代码中知道,我只需要输入一次格式字符串,它就会替换所有 %s & %<s 的实例。</p><p> 很好奇这个名字叫什么!</p></div>

[英]What is this %<s called?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM