Normally when we use constructor methods(new key word) to create instances of a class. And in post i am going to explain another way of create object which is static factory methods.For an example we can take one of factory method implemented in java.lang.Boolean.
public static Boolean valueOf(boolean b){ return b? Boolean.TRUE : Boolean.FALSE; }Providing factory method to create objects rather than using constructors has both advantaged and disadvantages.
Advantages of having Factory methods to create instances
- Factory methods have a valid name
Imaging you have a Shape class and it has a constructor which accept one int parameter which is the number of edges.If parameter is 3 it returns a triangle.So the client code which use this constructor is not too clear since constructor method does not make a sense about the object which is going to retrieve. But if we have a static factory method called getTriangle() which returns a triangle shape instance, it would be more readable than having a constructor method.
- Do not need to create new object in each time
This is the implementation of singleton pattern. This technique is very useful is cases of cost of creating an instance is too high and where we can share a single object. One of the advantage of using this concept is we don't need equals( ) method for comparisons and we can simple check the equality by == operator.
- Factory methods can returns any sub type of their return type
One application of this flexibility is that an API can return object without making their classes public.For an example look at the java.util.Collections. In this case interfaces provide return types for static factory methods. And those static factory methods are put in a non instantiable class.
- Reduce the overhead of creating parameterized type instances
Instead of this kind of constructor methods we can have a factory method which can be reusable with less effort.
Disadvantages of having Factory methods to create instances
- It is hard to distinguish factory static method form other available static methods
- Non public classes cannot be sub classed(If we have factory method to create instance then we can make that class a private)
No comments:
Post a Comment