public class SingletonTest1 { public static void main(String[] args) { Singleton s1 = Singleton.GetInstance(); Singleton s2 = Singleton.GetInstance(); //if(s1==s2) if(s1.equals(s2)) { System.out.println("两个对象是相同的实例"); } System.out.println(); } } class Singleton { private static Singleton instance = null; private Singleton(){} public static synchronized Singleton GetInstance() { if(instance == null) { instance = new Singleton(); } return instance; } } public class SingletonTest2 { public static void main(String[] args) { Singleton s1 = Singleton.GetInstance(); Singleton s2 = Singleton.GetInstance(); //if(s1==s2) if(s1.equals(s2)) { System.out.println("两个对象是相同的实例"); } System.out.println(); } } class Singleton { private static final Singleton instance = new Singleton(); private Singleton(){} public static Singleton GetInstance() { return instance; } } import javax.swing.*; import java.awt.*; import java.awt.event.*; public class SingletonTest3 extends JFrame implements ActionListener { JDesktopPane desktop; ToolBar1 tb = null; public SingletonTest3() { super("设计模式之单例模式"); setSize(640,480); desktop = new JDesktopPane(); setContentPane(desktop); setJMenuBar(createMenuBar()); desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE); } public JMenuBar createMenuBar() { JMenuBar menuBar = new JMenuBar(); JMenu menu = new JMenu("文件"); menuBar.add(menu); JMenuItem menuItem = new JMenuItem("工具栏"); menuItem.setActionCommand("new"); menuItem.addActionListener(this); menu.add(menuItem); menuItem = new JMenuItem("退出"); menuItem.setActionCommand("quit"); menuItem.addActionListener(this); menu.add(menuItem); return menuBar; } public void actionPerformed(ActionEvent e){ if("new".equals(e.getActionCommand())){ createFrame(); }else{ quit(); } } public void quit() { System.exit(0); } public void createFrame() { if(tb == null ) { tb = ToolBar1.getInstance(); desktop.add(tb); }else{ if(tb.isClosed()) { desktop.add(tb); tb.setVisible(true); } } } public static void main(String[] args) { //JFrame.setDefaultLookAndFeelDecorated(true); SingletonTest3 frame = new SingletonTest3(); frame.setVisible(true); } } class ToolBar1 extends JInternalFrame { private static final ToolBar1 instance = new ToolBar1(); public ToolBar1() { super("工具栏",true,true,true,true); JButton btn = new JButton("工具栏"); getContentPane().add(btn); setSize(100,320); setVisible(true); } public static ToolBar1 getInstance() { return instance; } }