简体   繁体   中英

Static factory methods instead of constructors

I've been researching this after I read Joshua Block's Effective Java Book, Item 1, about using factory static methods instead of constructors. There in the text he defends the use, whenever possible and cites, among other justifications, the possibility of implementing the Singleton or Flyweight standards. It also cites the case of the Boolean class, which wisely uses Flyweight through the valueOf (boolean) method:

public static Boolean valueOf(boolean b) {
return b ? Boolean.TRUE : Boolean.FALSE;
}

My question is: I understand the advantages of using these patterns, but could not be implemented in the constructor itself? Their use alone does not justify the creation of a static factory method.

but could not be implemented in the constructor itself?

No: new , by specification, always creates a new instance (or fails), so new Boolean(b) would always return a new instance of Boolean .

Boolean.valueOf returns a pre-existing instance. This is desirable, because there are only two possible values, so there is simply no point in creating more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM