Hi friend,
class Singleton{
public static void main(String[] args) {
System.out.println("First person getting the spoon");
SingleSpoon spoonForFirstPerson =
SingleSpoon.getTheSpoon();
if(spoonForFirstPerson != null)
System.out.println(spoonForFirstPerson);
else
System.out.println("No spoon was available");
System.out.println("");
System.out.println("Second person getting a spoon");
SingleSpoon spoonForSecondPerson = SingleSpoon.getTheSpoon();
if (spoonForSecondPerson != null)
System.out.println(spoonForSecondPerson);
else
System.out.println("No spoon was available");
System.out.println("");
System.out.println("First person returning the spoon");
spoonForFirstPerson.returnTheSpoon();
spoonForFirstPerson = null;
System.out.println("The spoon was returned");
System.out.println("");
System.out.println("Second person getting a spoon");
spoonForSecondPerson = SingleSpoon.getTheSpoon();
if (spoonForSecondPerson != null)
System.out.println(spoonForSecondPerson);
else
System.out.println("No spoon was available");
}
}
-----------------------------
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class SingleSpoon extends JFrame{
JButton button = new JButton();
public SingleSpoon(){
try{
init();
}
catch(Exception e){
e.printStackTrace();
}
}
private void init() throws Exception {
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
button.setText("Show Singleton Frame");
button.setBounds(new Rectangle(12, 12, 220, 40));
button.addActionListener(new java.awt.event.ActionListener(){
public void actionPerformed(ActionEvent e){
button_actionPerformed(e);
}
});
this.getContentPane().setLayout(null);
this.getContentPane().add(button, null);
}
void button_actionPerformed(ActionEvent e) {
TestSingleSpoon singletonFrame = TestSingleSpoon.getInstance();
singletonFrame.setVisible(true);
}
public static void main(String[] args) {
SingleSpoon frame = new SingleSpoon();
frame.setSize(300, 250);
frame.setVisible(true);
}
}
----------------------------------------------
read for more information,
http://www.roseindia.net/javatutorials/J2EE_singleton_pattern.shtml