本文介绍了如何消除对Java Bean的严格依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对DIP原则有疑问。其中一项准则规定,我们不应保留对具体类的引用(如果更改,则我将必须修改所有使用该类的客户端)。因此,当我使用POJO时可以遵循什么准则?例如:



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

  class Foo {
private字符串一;
私有字符串二;

//获取器和设置器
}

多个客户实例化例如,将此对象保留在数据库中

 类Client1 {

私有FooDao dao ;

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

public voidpersist(){
//硬编码
Foo foo = new Foo();
foo.setOne( something ...);
dao.save(foo); }
}

类Client2 {

私人FooDao岛;

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

}}

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

如果我将任何属性添加或更改为 Foo每个客户都必须更改班级,因此请遵循此指南,如何避免这种情况?



谢谢!

解决方案

@chrylis的评论很明确。罗伯特·马丁(Robert Martin)在清洁代码:对象和数据结构的第6章中对此进行了介绍。

OOP的定义是天真的,这里的一切都是对象,没有数据结构。

那么暴露数据和行为的类又如何呢?

对于原始问题:依赖倒置原则适用于对象,而不适用于Java Beans等数据结构。 p>

I've a question about DIP Principle. One of the guidelines says that we should not hold references to a concrete class (if it changes then I'll have to modify all clients that use it). So, what can I follow this guideline when I use POJOs ? For Example:

I have a Bean 'Foo' with some attributes (it could represent a Domain object)

class Foo {
   private String one;
   private String two;

  //getters and setters
}

Multiple clients instantiate this object, for example, to persist it in the Database

   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);
         }
       }

If I add or change any attribute to 'Foo' class every client would have to change, so follow this guideline how can I avoid that?

Thanks!

解决方案

The comment from @chrylis is spot on. Robert Martin covers this in chapter 6 of Clean Code: Objects and Data Structures.

The definition of OOP where everything is an object, and there are no data structures, is naive.

So what about classes that expose both data and behavior?

To the original question: the Dependency Inversion Principle applies to objects, not to data structures like Java Beans.

这篇关于如何消除对Java Bean的严格依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 12:00