单值强类型Property属性包装对应的设计模式名称是什么
强类型属性包装设计模式名称咨询
模式核心特征
- 在POJO中使用
public final修饰符定义属性对象,每个属性作为特定类型值的持有者/包装器 - 属性类内置对应值的getter/setter方法,还可承载额外自定义逻辑
- 与*Property Container(属性容器)*设计模式存在明显区别:后者采用单一容器存储多种类型的属性值,该模式下每个属性实例仅持有单个值,可始终保持强类型特性
代码示例
实体类使用样例
public class User extends Entity<User> { private static final Structure<User> STRUCTURE = Structure.of(User.class, User::new) .addPrimaryKey("user_id", UUID).property((e) -> e.userID).setDefault(() -> UUID()).build() .addIndex("username", VCHARS_50).property((e) -> e.username).build() .addIndex("email", VCHARS_255).property((e) -> e.email).build() .add("password", VCHARS_255).property((e) -> e.passwordHash).build() .add("privacy_policy_accepted", EPOCH).property((e) -> e.ppAccepted).setDefault(() -> now()).build() .add("tos_accepted", EPOCH).property((e) -> e.tosAccepted).setDefault(() -> now()).build() .add("registration_date", EPOCH).property((e) -> e.registrationDate).setDefault(() -> now()).build() .buildFor(Schema.MASTER); public final Property<UUID> userID = new Property<>(); public final Property<String> username = new Property<>(); public final Property<String> email = new Property<>(); public final Property<String> passwordHash = new Property<>(); public final Property<Long> ppAccepted = new Property<>(); public final Property<Long> tosAccepted = new Property<>(); public final Property<Long> registrationDate = new Property<>(); public User() { super(STRUCTURE); } public void hashAndSetPassword(String password) { this.passwordHash.set(Argon2Factory.create(Argon2Types.ARGON2id).hash(3, 102800, 1, password.toCharArray())); } public boolean verifyPassword(String attempt) { return Argon2Factory.create(Argon2Types.ARGON2id).verify(passwordHash.get(), attempt.toCharArray()); } }
属性基类实现
public class Property<T> { private T currentValue; public void set(T newValue) { this.currentValue = newValue; } public T get() { return this.currentValue; } @Override public boolean equals(Object o) { return Objects.equals(currentValue, o); } @Override public int hashCode() { return Objects.hashCode(currentValue); } @Override public String toString() { return String.valueOf(currentValue); } }
扩展能力与设计优势
- 可对
Property类进行扩展改造实现更多实用能力:例如记录实例创建时从数据库读取的原始值,支持属性自行判断当前值与原始值是否存在变更,该能力可用于识别数据库中需要更新的数据列 - 最显著的优势是无需为每个新增属性单独编写getter和setter方法,相关能力已由
Property类内置;如果单个属性需要特殊处理逻辑,也可按需重写对应的get/set逻辑
提问诉求
我在开发Web框架时,为了彻底移除反射、注解处理器等非显式的“黑魔法”逻辑,自然演化出了这种设计实现,但目前无法在公开资料中检索到该模式的对应信息,希望确认其正式名称,以便研究该设计方案潜在的缺陷。
内容的提问来源于stack exchange,提问作者justis
相关产品推荐
相关产品推荐

