Java Reference
In-Depth Information
What happens if the Singleton is serialized and then de-serialized? This situation
may cause another instance of the object to be returned upon deserialization. To pre-
vent this issue from occurring, be sure to implement the r eadResolve() method, as
demonstrated in solution 1. This method is called when the object is deserialized, and
simply returning the instance ensures that another instance is not generated.
Solution 2 demonstrates a different way to create a Singleton, which is to use a Java
enum rather than a class. Using this approach can be beneficial because an enum
provides serialization, prohibits multiple instantiation, and allows you to work with
code more concisely. In order to implement the enum Singleton, create an enum and
declare an INSTANCE element. This is a static constant that will return an instance of
the enum to classes that reference it. You can then add elements to the enum that can
be used by other classes within the application to store values.
As with any programming solution, there is more than one way to do things. Some
believe that the standard Singleton pattern demonstrated in solution 1 is not the most
desirable solution. Others do not like the enum solution for different reasons. Both of
them will work, although you may find that one works better than the other in certain
circumstances.
5-4. Generating Instances of a Class
Problem
In one of your applications, you would like to provide the ability to generate instances
of an object on the fly. Each instance of the object should be ready to use, and the ob-
ject creator should not need to know about the details of the object creation.
Solution
Make use of the factory method pattern to instantiate instances of the class while ab-
stracting the creation process from the object creator. Creating a factory will enable
new instances of a class to be returned upon invocation. The following class represents
a simple factory that returns a new instance of a Player subclass each time its cre-
atePlayer(String) method is called. The subclass of Player that is returned
depends upon what String value is passed to the createPlayer method.
Search WWH ::




Custom Search