gpt4 book ai didi

java - 如何消除对 Java Bean 的硬依赖

转载 作者:行者123 更新时间:2023-12-02 01:37:31 25 4
gpt4 key购买 nike

我有一个关于 DIP 原理的问题。其中一项指导方针说,我们不应该保留对具体类的引用(如果它发生变化,那么我将不得不修改所有使用它的客户端)。那么,当我使用 POJO 时,我可以遵循什么准则呢?例如:

我有一个带有一些属性的 Bean 'Foo'(它可以代表一个 Domain 对象)

class Foo {  
private String one;
private String two;

//getters and setters
}

多个客户端实例化该对象,例如将其保存在数据库中

   class Client1 {   

private FooDao dao;

Client1(FooDao dao){
this.dao = dao;
}

public void persist() {
//hard coding
Foo foo = new Foo();   
foo.setOne("something...");
dao.save(foo); }
}

class Client2 {

private FooDao dao;

  Client2(FooDao dao){   
 this.dao = dao;

   } 

public void persist() {   
Foo foo = new Foo();   
foo.setOne("something...");
foo.setTwo("something...")   
dao.save(foo);
}
}

如果我向“Foo”类添加或更改任何属性,每个客户端都必须更改,因此遵循此指南如何避免这种情况?

谢谢!

最佳答案

@chrylis 的评论很正确。 Robert Martin 在《简洁代码:对象和数据结构》的第 6 章中介绍了这一点。

Objects hide their data behind abstractions and expose functions that operate on that data. Data structures expose their data and have no meaningful functions. (page 95)

OOP 的定义(一切都是对象,没有数据结构)是幼稚的。

Mature programmers know that the idea that everything is an object is a myth. Sometimes you really do want simple data structures with procedures operating on them. (page 97)

那么公开数据和行为的类又如何呢?

Confusion sometimes leads to unfortunate hybrid structures that are half object and half data structure. They have functions that do significant things, and they also have either public variables or public accessors and mutators that, for all intents and purposes, make the private variables public, tempting other external functions to use those variables the way a procedural program would use a data structure. Such hybrids make it hard to add new functions but also make it hard to add new data structures. They are the worst of both worlds. Avoid creating them. (page 99)

对于最初的问题:依赖倒置原则适用于对象,而不适用于 Java Bean 等数据结构。

关于java - 如何消除对 Java Bean 的硬依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55012841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com