Logo 
Search:

Java Answers

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds
  Question Asked By: David L.   on Nov 29 In Java Category.

  
Question Answered By: Leroy Schmidt   on Nov 29

singleton  is not so much a class  as a design pattern to build something
that meets a given intent.

In the example of the Singleton design pattern, the intent is to ensure a
class only has one instance and provides a global point of access to it. It
ensures that all objects that use an instance of this class are using the
same instance.



Example



package singleton;
import javax.swing.*;

public class SingletonFrame extends JFrame {
private static SingletonFrame myInstance;

// the constructor
private SingletonFrame() {
this.setSize(400, 100);

this.setTitle("Singleton Frame. Timestamp:" +
System.currentTimeMillis());

this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
}

public static SingletonFrame getInstance() {
if (myInstance == null)
myInstance = new SingletonFrame();

return myInstance;
}

}

First of all, notice that the class only has one constructor and its access
modifier is private. Secondly, to get an instance of that class, you have
the static getInstance method, and there is also a static variable called
myInstance (of type SingletonFrame). The getInstance method returns the
myInstance variable. The method checks if myInstance is null and, if so,
calls the constructor.

Share: 

 

This Question has 2 more answer(s). View Complete Question Thread

 


Tagged: