java单例模式

来源:互联网 发布:便宜的椅子 知乎 编辑:程序博客网 时间:2024/06/09 22:03

单例模式:一个类有且仅有一个实例,并且自行实例化向整个系统提供

单例模式的要点:一是某个类只能有一个实例;二是它必须自行创建这个实例;三是它必须自行向整个系统提供这个实例。

1、私有化静态属性(private static A model;)

2、私有化构造方法(private A(){})

3、提供公用的静态的方法(public static A getA(){

if(null == model){

model = new A();

}

return model;

})

方式一:
public class Singleton {private static final Singleton singeton = new Singleton();private Singleton(){}public static Singleton getSingleton(){return singeton;}    }


/*功能名称:单例模式时间:2014.3.28作者:张星晨*/class SingletonDemo{/*单例模式:通过私用的静态的属性,私有化构造方法,和公有的静态的获得实例的方法实现创建出单个对象(因为每new一次就创建一次对象,但是静态static是开辟一次内存空间,所以才能用static完成创建同一对象)*/ private static SingletonDemo s;//私有的静态属性private SingletonDemo(){};//私有化构造方法,下面main方法中无法调用私有的构造方法new创建对象//公有的静态获得实例方法public static SingletonDemo get(){if(s == null){s = new SingletonDemo();}return s;}public class TestSingleDemo{public static void main(String[] args){SingletonDemo s1 = SingletonDemo.get();//因为构造函数被私有化只能通过类调用公有的静态方法,而无法通过new来创建对象SingletonDemo s2 = SingletonDemo.get();System.out.println(s1 == s2);//ture(创建的是同一个对象【在静态区中】)}/*如果不使用单例模式是创建的两个对象public static void main(String[] args){SingletonDemo s1 = new SingletonDemo();SingletonDemo s2 = new SingletonDemo();System.out.println(s1 == s2);//false(创建的是两个对象)}*/}


0 0