Instead of creating objects using new operator you can also use static method to instantiate a class.
Code listing:
// instantiating a class using constructor Dog dog = new Dog(); .......................................... // instantiating the class using static method Class Dog{ private Dog(){ } // factory method to instantiate the class public static Dog getInstance(){ return new Dog(); } }Using static factory methods have both advantages as well as disadvantages. Advantages:
- Static factory methods can have different name than class whereas constructors cannot: As methods have names, they convey their purpose clearly as opposed to constructors. A class can have only one constructor with a given signature, developers get around this restriction by changing the order of parameters passed to constructors; In case of methods you can give a different name to resolve the issue.
- Static methods support conditional instantiation: Each time you invoke a constructor an object will get created but you might not want that. (for example, in singleton class you will maintain a single object). Or suppose you want to check some condition only then you want to create a new object.
-
Methods can return subtypes of return type: Suppose there is a class Animal and it has subclass Dog. We have static method with signature
public static Animal getInstance(){ ... } }
then method can return Both objects of type Animal and Dog which provides great flexibility.
- If constructor of the class is not public or protected then the class cannot be sub classed: If you ask if there is a workaround to this, there is not. But honestly, it is better as you cannot use inheritance and so you have to use composition which is always better than inheritance any day.
- Another disadvantage is you cannot differentiate between static factory methods and regular factory methods: There is no syntactical difference but if you follow some naming convention then it is easy to identify. For example, getInstance() is used in many frameworks to provide the instance of a class (java.util.Calendar, ).
- Pattern.compile
- Calendar.getInstance
- Collections.synchronizeCollection
- Effective Java 2nd edition by Joshua Bloch
- Factory Methods
No comments:
Post a Comment