单例模式(设计模式):为了解决保证工程仅有一个对象的问题
单例步骤:
–私有化构造方法
–在本类中定义一个私有化的静态的实例对象
–在本类中定义一个公有化的静态的获取实例化对象的方法
看一个例子:使用单例的JFrame
public class MyFrame extends JFrame {
private static MyFrame Mf;
public static MyFrame getMf() {
if (Mf == null) {
synchronized (MyFrame.class) {
if (Mf == null) {
Mf = new MyFrame();
}
}
}
return Mf;
}
private MyPanle mp = new MyPanle();
private MyFrame() {
this.setBounds(0, 0, 300, 300);
this.setTitle("服务端界面");
this.add(mp);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
int dialog = JOptionPane.showConfirmDialog(mp, "確定要退出嗎?", "溫馨提示", 0);
if (dialog == JOptionPane.OK_OPTION) {
System.exit(0);
}
}
}
);
}
public MyPanle getMp() {
return mp;
}
public void setMp(MyPanle mp) {
this.mp = mp;
}
public static void setMf(MyFrame mf) {
Mf = mf;
}
}