【设计思想学习笔记】 Abstract-document

【设计思想学习笔记】 Abstract-document

来自于对github上的设计思想图谱项目学习总结https://github.com/HotPotAndMe/java-design-patterns

1.导言

实现无类型语言的灵活性并保持类型安全

Achieve flexibility of untyped languages and keep the type-safety
在这里插入图片描述

2.应用

1.动态增加新属性

2.灵活地管理树状结构

3.实现低耦合系统

3.代码

Document

首先是处于继承顶端的Document

/**
 * Document interface
 */
public interface Document {
   

  /**
  *
  */
  Void put(String key, Object value);

  /**
   * Gets the value for the key
   *
   * @param key element key
   * @return value or null
   */
  Object get(String key);

  /**
   * Gets the stream of child documents
   *
   * @param key         element key
   * @param constructor constructor of child class
   * @return child documents
   */
  <T> Stream<T> children(String key, Function<Map<String, Object>, T> constructor);
}

所有最基础接口直接extend Document接口

例如图谱中提到的HasPrice等接口

public interface HasPrice extends Document {
   

  String PROPERTY = "price";

  default Optional<Number> getPrice() {
   
    return Optional.ofNullable((Number) get(PROPERTY));
  }

}
public interface HasType extends Document {
   

  String PROPERTY = "type";

  default Optional<String> getType() {
   
    return Optional.ofNullable((String) get(PROPERTY));
  }

}
public interface HasModel extends Document {
   

  String PROPERTY = "model";

  default Optional<String> getModel() {
   
    return Optional.ofNullable((String) get(PROPERTY));
  }

}

​ 通过default实现派生对该类的访问

​ 现在有一个问题,我们在HasPrice中并没有实现get方法,那为什么可以使用get方法呢,因为我们extends Document接口的是一个接口,所以暂时可以不用实现接口中的方法而提前使用。我们将在什么时候实现get方法这个问题先放一下。

​ 首先我们可以分析一下这三个类,他定义了三个类根本上是标记了属性,又将属性与属性具体的值分离开来,完成了想要实现的解耦思想。

​ 接下来我们将看下一个接口part

public interface HasParts extends Document {
   

  String PROPERTY = "parts";

  default Stream<Part> 
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值