单例模式,就是采取一定的方法保证在整个软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得对象实例的静态方法。
2.分类 1)饿汉式 :适用于创建对象简单快捷步骤:
- 构造器私有化(封死new)
- 类的内部创建对象
- 向外暴露一个静态的公共方法用于获取该对象的地址
代码实现:
class Singleton1{
//类加载时就创建好对象
private static Singleton1 only=new Singleton1();
//构造器私有化,只有本类中才能创建对象
private Singleton1() {
}
//获取时直接return
public static Singleton1 getInstance(){
return only;
}
}
public class SingletonTest {
public static void main(String[] args) {
//new Singleton1(); 外部不能创建对象
Singleton1 singleton1 = Singleton1.getInstance();
Singleton1 singleton2 = Singleton1.getInstance();
System.out.println(singleton1==singleton2);//true 证明是同一个对象
}
}
优缺点:
1)优点:写法简单,在类加载时就完成了实例化,避免线程同步问题
2)缺点:没有达到懒加载的效果,如果从始至终都未使用到这个对象,势必会造成资源的浪费
步骤:
- 构造器私有化(封死new)
- 在本类中有引用用于指向对象
- 在公共静态方法中才创建对象
- 懒汉式是线程不安全的,可以使用同步代码块保证线程安全
代码实现
class Singleton2{
private static Singleton2 only;
//构造器私有化
private Singleton2() {
}
//获取时才创建
public static Singleton2 getInstance(){
//synchronized (Singleton2.class) {
if (only == null) {
only = new Singleton2();
}
return only;
//}
}
}
public class SingletonTest {
public static void main(String[] args) {
Singleton2 singleton3 = Singleton2.getInstance();
Singleton2 singleton4 = Singleton2.getInstance();
System.out.println(singleton3==singleton4);
}
}
优缺点:
1)优点:对象在获取的时候才创建,起到了懒加载的作用
2)缺点:存在线程安全问题,如果一个线程满足if条件进入创建对象,在这个对象创建的过程中,其他线程进来就会创建多个对象


![【Java设计模式[单例模式]】 【Java设计模式[单例模式]】](http://www.mshxw.com/aiimages/31/1027056.png)
