effective-java阅读01天

Item 1: Consider static factory methods instead of constructors

One advantage of static factory methods is that, unlike constructors, they have names
A second advantage of static factory methods is that, unlike constructors, they are not required to create a new object each time they’re invoked
A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type. 
A fourth advantage of static factories is that the class of the returned object can vary from call to call as a function of the input parameters. Any subtype of the declared return type is permissible. The class of the returned object can also vary from release to release
A fifth advantage of static factories is that the class of the returned object need not exist when the class containing the method is written. 

The main limitation of providing only static factory methods is that classes without public or protected constructors cannot be subclassed. 
A second shortcoming of static factory methods is that they are hard for programmers to find. This list is far from exhaustive:
Date d = Date.from(instant);
Set<Rank> faceCards = EnumSet.of(JACK, QUEEN, KING);
BigInteger prime = BigInteger.valueOf(Integer.MAX_VALUE);
StackWalker luke = StackWalker.getInstance(options);
Object newArray = Array.newInstance(classObject, arrayLen);
FileStore fs = Files.getFileStore(path);
BufferedReader br = Files.newBufferedReader(path);
List<Complaint> litany = Collections.list(legacyLitany);

结论:优先考虑静态工厂,静态工厂不合适,再考虑public constructors

Item 2: Consider a builder when faced with many constructor parameters

This client code is easy to write and, more importantly, easy to read. The Builder pattern simulates named optional parameters as found in Python and Scala.
The Builder pattern is well suited to class hierarchies.
the Builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters

Item 3: Enforce the singleton property with a private constructor or an enum type

 Making a class a singleton can make it difficult to test its clients
 The main advantage of the public field approach is that the API makes it clear
that the class is a singleton: the public static field is final, so it will always contain
the same object reference. The second advantage is that it’s simpler.
a single-element enum type is often the best way to implement a singleton

Item 4: Enforce noninstantiability with a private constructor

Item 5: Prefer dependency injection to hardwiring resources

Item 6: Avoid creating unnecessary objects

在这里插入图片描述
在这里插入图片描述

Item 7: Eliminate obsolete object references

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值