所谓类的单态设计模式,就是采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法。
如果要让类在一个虚拟机中只能产生一个对象,首先必须将类的构造方法的访问权限设置为private,这样就不能用new操作符在类的外部产生类的对象了,但在类内部仍可以产生该类的对象。因为在类的外部开始还无法得到类的对象,只能调用 该类的某个静态方法以返回类内部创建的对象,静态方法只能访问类中的静态成员变更,所以,指向类内部产生的该类对象的变更也必须定义成静态的。例子
public class TestSingle
{
private static final TestSingle onlyOne= new TestSingle();
public static TestSingle getTestSingle(){
return onlyOne;
}
private TestSingle(){}
}
public class SchematicDialog extends JDialog {
private static SchematicDialog instance = null;
private SchematicDialog() {
super(JFrame.getFrames()[0]);
super.add(SchematicMainPanel.getInstance());
// super.setSize(1000, 600);
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
// super.setLocation((int) (dimension.getWidth() - super.getWidth()) / 2, (int) (dimension.getHeight() - super.getHeight()) / 2);
super.setSize((int) dimension.getWidth() - 10, (int) dimension.getHeight() - 50);
super.setModal(false);
super.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
SchematicLoadData.getInstance().clearSchematicLayers();
}
});
}
public void setVisible(boolean b) {
SchematicMainPanel.getInstance().getLayoutComboBox().setSelectedIndex(0);
super.setVisible(b);
}
public static SchematicDialog getInstance() {
if (instance == null) {
instance = new SchematicDialog();
}
return instance;
}
}
单态设计模式
最新推荐文章于 2018-05-10 17:47:47 发布