Using Static Methods to create a Singleton


Prerequisites

This Magercise covers some aspects of method access and static variables and methods by creating a PersonFactory class. This new class acts as a singleton factory class to create Persons.

Static variable declarations are discussed in detail in the course notes.

Work Location

Perform all work for this magercise in VisualAge project MageLang Magercises, package magercises.singleton.

If this project does not appear in your Workspace add it from the repository (if it exists there) or create a new project using this name.

Tasks

Perform the following tasks:

  1. Change the constructor for Person so that only other classes in the same package can use it.

  2. Create the PersonFactory class with a private constructor that does nothing.

  3. Add a static variable to the PersonFactory class to hold an instance of that class.

  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.

  5. Add the method newPerson to the PersonFactory class to act as a surrogate for the now hidden constructor for Person.

  6. Modify the main method to use the new factory class.

The task numbers above are linked to the step-by-step help page. Also available is a complete solution to the problem, and expected behavior, to demonstrate it.

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