Reading <Effective Java>

来源:互联网 发布:qq群搜索排名优化 编辑:程序博客网 时间:2024/04/20 04:36

In item 3 of Effective Java, a new way of creating an Singleton class with Enum is introduced.

public enum Singleton{

INSTANCE;

public void method{ ... }

}

And just access the singleton with Singleton.INSTANCE

This is pretty neat to implement and I shall try it out next time when I am working on Singleton.


Item 5: avoid creating unnecessary objects

An example is give in the book:

public boolean isBabyBoomer(){

Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));

}

compared to

static {

Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));

}

public boolean isBabyBoomer(){

return .... // something that uses gmtCal...

}

The second approach is much more efficient as only one instance of Calendar is obtained, instead of creating one each time isBabyBoomer is called.



0 0
原创粉丝点击