0

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.

deldev
  • 1,296
  • 18
  • 27
  • You can check this https://javarevisited.blogspot.com/2017/02/5-difference-between-constructor-and-factory-method-in-java.html – Sambit Oct 24 '19 at 15:17

1 Answers1

1

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.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • And how to deal with a dependency injection issue when you become a private builder? Is it possible to use DI when using this building strategy? – deldev Oct 24 '19 at 17:54
  • @dellasavia I'm not sure what you are asking. Consider that constructors are effectively just special static methods: the DI implications of using static factory methods are the same as using constructors – Andy Turner Oct 26 '19 at 07:46
  • I did mean when using a framework to inject like Spring. How it knows which is the constructor method that will be used? – deldev Oct 26 '19 at 12:54
  • 1
    @dellasavia I can't answer for Spring, but with Guice you have to have an explicit `@Provides` method. – Andy Turner Oct 26 '19 at 12:56