In Item-1 of Effective Java, Mr. Bloch emphasize why and how it is important to use Static Factory methods instead of constructors.
Here is goofy and wasteful way to get Boolean instances
Here is shiny and frugally way to get immutable Boolean instance with static factory method
Lets go over advantages of using static factory methods
1.) Unlike constructors, the have names. If parameters to a constructor do not describe object being returned, a static factory with well choosen name is easier to use and resulting client code easier to read.
Another example is multiple constructors with same signature as I met in stackoverflow.
Two constructors with same signature doing different things.
Can be managed by using static factory methods.
2.) Unlike constructors, they are not required to create a new object each time they're invoked. This is demonstrated as in boolean example above and important to use system resources frugally by avoiding unnecessary instance creation.
3.) A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type. Mr Bloch exemplifies this advantage with Service Provider Framework pattern.
Finally, he give a list of some common method names to statis factory methods.
- valueOf
- of
- getInstance
- newInstance
- getType
- newType
1 comment:
شركة المثالية للتنظيف
شركة تنظيف خزانات
شركة صيانة مسابح
شركة مكافحة النمل الابيض
Post a Comment