传递给构造函数或创建

时间:2018-09-10 05:29:07

标签: oop

尽管两者都是正确的,但是建议采用以下哪种方式:

public class MyService(MyRepository ...) {
    ...
}

public class MyService() {
    myRepository = CreateMyRepository();
}

protected MyRepository CreateMyRepository() {
    ...
}

前者意味着应该成为存储库的公共获取者,这违背了仅允许服务控制存储库的目的。

1 个答案:

答案 0 :(得分:0)

这取决于您的要求,但我建议如下例所示。

公共构造函数在依赖注入中很有用。

受保护的构造方法可以用于其自己的类和子类(在 Singleton Design Pattern 中有用)。对于Abstract类,它也是有用的构造函数。

私有构造函数可以在其自己的类中使用,并确保最多只能有一个对象(在 Singleton Design Pattern 中有用, 构建器设计模式 )。

 class MyService {
      private MyRepository myRepository;

      public MyService(MyRepository myRepository){
          this.myRepository= myRepository;  

      }

      public String getMyRepository() { return myRepository; }

       public void setMyRepository(MyRepository myRepository)
       {    
       this.myRepository= myRepository;
      }

    }