在Java中创建对象的最佳实践 [英] Best practice to creating Objects in java

查看:114
本文介绍了在Java中创建对象的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Joshua Bloch撰写的 Effective Java 书。在第一章中,他说使用工厂而不是构造函数,并列出了这种方法的优缺点。据我所知,缺点与对象构造没有密切关系。

I'm reading the Effective Java book by Joshua Bloch. In the first chapter, he says to use factories instead of constructors and lists the advantages and disadvantages of this approach. As far as I see disadvantages are not closely related to to object construction.

此外,Bloch说Java Bean样式的构造也有缺点。
来源: http://www.javapractices.com/topic/TopicAction .do?Id = 84

Moreover, Bloch says that Java Bean style of construction has disadvantages as well. Source: http://www.javapractices.com/topic/TopicAction.do?Id=84

好,所以使用构造函数不是很好,Java Bean不是很好,工厂很好,所以可以做一些缓存查找并避免创建额外的对象(取决于情况,有时您不希望缓存)。

OK, so using constructors is not great, Java beans are not great, factories are nice, so you can do some cache lookups and avoid creating extra objects (depends on the situation, sometimes you dont want caching).

如果我尽量避免使用构造函数和Java Bean,应该如何创建一个对象?

How am I supposed to create an object if I try to avoid constructors and java beans?

我遗漏了一点?最佳做法是什么?

Am I missing a point? What is the best practice?

编辑:

class Foo{
   private Foo(){}

   public Foo Create(){
      return new Foo();
   }

}


推荐答案

使用构造函数,直到您开始感受到Bloch提到的缺点为止。然后考虑工厂,依赖注入或其他方法是否更好。

Use constructors until you start to feel the disadvantages Bloch mentions. Then consider whether factories, dependency injection, or some other approach is better.

这篇关于在Java中创建对象的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆