Help: Using Static Methods to create a Singleton


Help is available for each task, or you can go straight to the solution source code.

Task 1

Change the constructor for Person so that only other classes in the same package can use it.
Make the constructor "friendly" by removing the public keyword from its signature.

Task 2

Create the PersonFactory class with a private constructor that does nothing.
Create a constructor for PersonFactory with an empty body, add the private keyword to the signature.

Task 3

Add a static variable to the PersonFactory class to hold an instance of that class.
Add the static variable "instance" with the type PersonFactor. It should also be private.

Task 4

Add the method instance to the PersonFactory class. It will always return the single instance of the PersonFactory class, which is held in the static variable, instance.
Before returning the value of the variable, it must check if it is null, setting it to a new instance of the PersonFactory class if it is.

Task 5

Add the method newPerson to the PersonFactory class to act as a surrogate for the now hidden constructor for Person.
This method takes a string name as an argument, creates a new Person with that name, and returns it.

Task 6

Modify the main method to use the new factory class.
Replace all calls to the Person constructor with calls to the PersonFactory method newPerson. Use the static method PersonFactory.instance to retrieve an instance of the PersonFactory.

Copyright © 1996-1997 MageLang Institute. All Rights Reserved.