Singleton 模式
单例模式:指的是始终保持一个实例的意思。
?
单例模式始终确保一个类只有一个实例,这个类称为单例类。
单例:是某个类但只能有一个实例;必须自行创建这个实例;必须自行向整个系统提供整个实例。
?
(1)
public class Singleton{
???? private Singleton(){}?????????? //构造方法必须私有
????
???? private static Singleton s = new Singleton();
?
???? public static Singleton getInstance(){
????????? return s;
???? }
}
?
(2)第二个写法.最好加上synchronized ,实现同步
public class Singleton{
???? private Singleton(){}?????????? //构造方法必须私有
????
???? private static Singleton s?= null;
?
???? public static synchronized? Singleton getInstance(){
????????? if(s==null){
?????????????? s = new Singleton ();
????????? }???
????????? return s;???????
???? }
}