【问题标题】:Structural design patterns: (Private class data) Is there a difference between these two examples结构设计模式:(私有类数据)这两个例子有区别吗
【发布时间】:2017-12-05 08:04:56
【问题描述】:

以下是 sourcemaking.com 中此模式的示例:

https://sourcemaking.com/design_patterns/private_class_data

有两个例子,划掉的主类和包含数据类的主类。

我的问题只是以下内容与链接中给出的正确实现之间有什么区别:

public class MainClass {

    private final <Type> attribute1;
    private final <Type> attribute2;
    private final <Type> attribute3;

    public MainClass(<Type> attribute1, <Type> attribute2, <Type> attribute3 {
        this.attribute1 = attribute1;
        this.attribute2 = attribute2;
        this.attribute3 = attribute3;
    }
}

干杯

【问题讨论】:

  • 您的问题中缺少泛型类型定义
  • 我认为从业务逻辑外部化数据类的好处在更大的类中变得更加明显。这个小班并不能真正起到示范作用。
  • 请注意,模式不是来自 GoF。在我看来,它更像是一种反模式。

标签: java design-patterns encapsulation design-principles


【解决方案1】:

您的代码不是该模式的示例。划掉的模型是不能做的。

您需要一个单独的 Java 对象来保存属性,并且该页面准确列出了该模式存在的原因 - 以限制字段的公开

从这一点开始

主类必须通过数据类的构造函数初始化数据类

数据对象可以声明为final

【讨论】:

  • 我认为 OP 理解这一点,但在他的示例中,将字段声明为 final 以确保它们之后不会被修改。我认为这就是他的观点。
  • 区别还是有一个单独的对象。并且该对象可以充当不需要从顶级类公开的其他业务逻辑的外观
  • 立面角度很有意思,谢谢大家的回复
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多