这算是低耦合高内聚吗?有改善的机会吗?

Is this considered low coupling & high cohesion? Any chance to improve?

我正试图掌握 Robert C. Martin 的 SOLID 原则。目前我正在研究低耦合和高内聚。我已经创建了一些代码来代表我目前对该主题的理解。你们能告诉我是否在正确的轨道上吗?有机会改进当前的设计吗?

创建两个地址并将其分配给员工的主应用程序:

public class App {

    public static void main(String[] args) {
        Address homeAddress = new HomeAddress("This is my Home Address");
        Address workAddress = new WorkAddress("This is my Work Address");        
        Employee employee = new Employee(homeAddress, workAddress);

        employee.getAddresses();
    }

}

员工class:

public class Employee {

    private Address homeAddress;
    private Address workAddress;

    Employee(Address homeAddress, Address workAddress) {
        this.homeAddress = homeAddress;
        this.workAddress = workAddress;
    }

    public void getAddresses() {
        System.out.println("homeAddress: " + homeAddress.getAddress());
        System.out.println("workAddress: " + workAddress.getAddress());
    }

}

地址接口:

public interface Address {

    String getAddress();

}

特定地址实现 1(家庭地址):

public class HomeAddress implements Address {

    String specificAddress;

    public HomeAddress(String specificAddress) {
        this.specificAddress = specificAddress;
        System.out.println("In HomeAddress Constructor");
    }

    public String getAddress() {
        return specificAddress;
    }
}

特定地址实现 2(WorkAddress):

public class WorkAddress implements Address {

    String specificAddress;

    public WorkAddress(String specificAddress) {
        this.specificAddress = specificAddress;
        System.out.println("In WorkAddress Constructor");
    }

    public String getAddress() {
        return this.specificAddress;
    }
}

任何 help/feedback 将不胜感激!提前致谢。

马克

这是一个小示例,但可以根据 coupling/cohesion 进行改进。

对象是内聚的。为什么?在 Employee 对象中,构造函数和 getAddresses()(顺便说一下应该称为 printAddresses())都引用两个实例变量(这意味着它们关注同一件事)。 Address 个对象也是如此。

耦合部分我觉得你可以做得更好。就目前而言,Employee 对象 "knows about"(即耦合到)Address 对象的内部表示。那是因为您 "export" 来自 Address 对象的数据(字符串)而不是在数据所在的地方打印它。

这会使您的对象更加耦合,并且会导致 Address 对象中的任何更改(例如引入 Street 和 City 等)泄漏到 Employee。所以它有真正的缺点。

解决方案是在 Address 中定义一个 print() 方法并在那里执行 System.out.println()。这符合其他概念,例如 Law of Demeter, Tell Don't Ask.