Moon Light Box

Time is Money

Java - getInstance VS new

| Comments

Usually, you write this syntax to create an instance.

Father myFather = new Father();

Then we consider family relation of a father and his children then write this.

public class Father {
    public Father() {
    }
}
public class ChildA {
    public void getFather() {
        return new Father();
    }
}
public class ChildB {
    public Father getFather() {
        return new Father();
    }
}
public class Family {
    public static void main(String[] args) {
        ChildA mChildA = new ChildA();
        ChildB mChildB = new ChildB();
        if (mChildA.getFather().equals(mChildB.getFather())) {
            System.out.println("Same father.");
        } else {
            System.out.println("Difference father.");
        }
    }
}

Oh my god, we get the terrible result.

Result:
Difference father.

We have to modify.

public class Father {
    private static Father mFather = new Father();
    public static Father getInstance () {
        return mFather;
    }
}
public class ChildA {
    public Father getFather() {
        return Father.getInstance();
    }
}
public class ChildB {
    public Father getFather() {
        return Father.getInstance();
    }
}

Summary :

getInstance() is not a Java reserved name.
But it is a potential standard which we want only one instance when class be created.

Comments

comments powered by Disqus