Over these years, I attempted to read Effective Java by Joshua Bloch.
But this time I am making a frank attempt
Chapter 2
1. Different ways a class allows a client to obtain an instance of itself
Static factory method
But this time I am making a frank attempt
Chapter 2
1. Different ways a class allows a client to obtain an instance of itself
- Calling public constructor
- Calling public static factory method
public class FormationMarker { private Float holeDepth; private Float bitDepth; public FormationMarker(Float holeDepth, Float bitDepth) { this.bitDepth = bitDepth; this.holeDepth = holeDepth; } public Float getHoleDepth() { return holeDepth; } public Float getBitDepth() { return bitDepth; } }
Accessor Class
public class Markers { public static void main (String args []) { FormationMarker formationMarker = new FormationMarker(1204.5f, 1689.2f); System.out.println(formationMarker.getBitDepth()+ " "+formationMarker.getHoleDepth()); } }
Output:
1689.2 1204.5
public class FormationMarkerFactory { private static FormationMarkerFactory instance; public FormationMarkerFactory getInstance () { if (null == instance) { instance = new FormationMarkerFactory(); } return instance; } private Float holeDepth; private Float bitDepth; public Float getHoleDepth() { return holeDepth; } public Float getBitDepth() { return bitDepth; } }
Advantages of static factory method
1. They have a name hence readable and easy to use.
2. They make the classes "instance controlled" meaning avoid creating un-necessary duplicate objects
Singleton classes make sure that there is only one instance created for the class
public class Singleton { private static Singleton instance = null; private Singleton () { } public static Singleton getInstance () { if (null != instance) { instance = new Singleton(); } return instance; } } a. private static Singleton instance - make sure that only one instance is created for the entire application b. private constructor makes sure that none other classes can create instances of Singleton class c. public static getInstance () - is a static factory method is the only way that clients can get access to the instance of Singleton class
3. We can define whatever return types we want, unlike constructor that does n't have return types. Disadvantages
1. Classes without a private or public constructors cannot be sub classed.
No comments:
Post a Comment