域 Class 与实现 Class

Domain Class vs Implementation Class

我正在阅读一篇关于 composition vs inheritance 的文章,该文章使用了术语 "domain class" 和 "implementation class"。作者特意说"Domain classes should use implementation classes, not inherit from them"。请解释域 class 和实现 class.

之间的区别

文中给出的实现示例class是ArrayList。它不是描述业务实体的代码的一部分,它只是一个常用的通用目的class。

这与他们提到的客户 class 形成对比。客户将是域的一部分 class,它描述了特定于业务的实体。

文章告诉您在创建域 classes 时不要像这样从实用程序 classes 扩展。

How to Misuse Inheritance - Example 2

Creating a domain-concept class by inheriting from an implementation class is a common misuse of inheritance. For example, suppose we want to do something with a certain segment of our customers. The easy and obvious thing to do is to subclass ArrayList, call it CustomerGroup, and start coding, right?

Wrong. That would be a cross-domain inheritance relationship, and those should be avoided:

1) ArrayList is a subclass of list already, a utility collection - an implementation class.

2) CustomerGroup is another subclass - a domain class.

3) Domain classes should use implementation classes, not inherit from them.

如果您需要实现 CustomerGroup class,它可以将 ArrayList 作为实例成员,如下所示:

public class CustomerGroup {
    private List<Customer> customers = new ArrayList<>();

    public List<Customer> getCustomers() {return customers;}
} 

但您不会使 class 本身成为 ArrayList 的子class。

原因是,当您子class 某些内容时,class 的用户将获得超级class 的所有功能,即使它不合适。您实际上并不需要域 class 来查看它的运行情况,只需查看 java.util.Properties 的源代码,它的设计很糟糕,扩展了 java.util.Hashtable。当您使用 Properties 对象时,您可以使用 Hashtable 中的方法,即使它们完全没有必要且令人困惑,并且使用 superclass 方法不起作用或导致问题。