Today my work tasks led me to read about static factory methods, which are a different approach to initializing Java classes.
Effective Java (Addison-Wesley 2018) helped me understand this concept, and here is my brief take on that reading:
Bottles moving through an actual factory.Bottles moving through an actual factory.
-Static factory methods are given names, which helps us as developers better and more quickly understand what they do.
-They save time and memory in your program, because they aren’t required to create new instances when they are run.
-They can create subtypes that differ from release to release. These subtypes don’t even have to have their class written at the time that the method is written.
-They certainly don’t solve every problem. They don’t scale well with growing parameters. But the example given in the book illustrates this concepts use:
<span>public</span> <span>static</span> <span>Boolean</span> <span>valueOf</span><span>(</span><span>boolean</span> <span>b</span><span>)</span> <span>{</span><span>return</span> <span>b</span> <span>?</span> <span>Boolean</span><span>.</span><span>TRUE</span> <span>:</span> <span>Boolean</span><span>.</span><span>FALSE</span><span>;</span><span>}</span><span>public</span> <span>static</span> <span>Boolean</span> <span>valueOf</span><span>(</span><span>boolean</span> <span>b</span><span>)</span> <span>{</span> <span>return</span> <span>b</span> <span>?</span> <span>Boolean</span><span>.</span><span>TRUE</span> <span>:</span> <span>Boolean</span><span>.</span><span>FALSE</span><span>;</span> <span>}</span>public static Boolean valueOf(boolean b) { return b ? Boolean.TRUE : Boolean.FALSE; }
Enter fullscreen mode Exit fullscreen mode
Here you dynamically return an initialized boolean with concise and easy-to-understand code. That is just simply worth it.
Cheers.
暂无评论内容