Java 单例设计模式

Singleton:单例模式

1.在整个应用程序中,一个类只有一个实例对象

2.这个实例对象只能通过本类中创建=====>私有化构造

3.别人还得使用,通过本类中创建的一个对外访问的接口,来返回本类的实例对象

实现单例的3种模式:

1.懒汉式:只有用户第一次调用getInstence()的时候,对象的唯一实例才会被调用

创建懒汉单例模式的步骤:

01.创建静态变量

private static Student stu;

02.私有化构造

private Student(){}

03.提供对外访问的接口

public static synchronized Student getInstence(){

if(stu==null){

stu=new Student();

}

return stu;

}

04.测试类中使用

Student.getInstence()

2.饿汉式:(推荐使用)在类加载的时候,单例对象就被创建,是线程安全的

创建饿汉单例模式的步骤:

01.创建静态变量

private static Student stu=new Student();

02.私有化构造

private Student(){}

03.提供对外访问的接口

public static synchronized Student getInstence(){

return stu;

}

04.测试类中使用

Student.getInstence()

3.双重校验锁:为了保证多线程情况下,单例的正确性

创建双重校验锁单例模式的步骤:

01.创建静态变量

private static Student stu;

02.私有化构造

private Student(){}

03.提供对外访问的接口

public static synchronized Student getInstence(){

if(stu==null){

synchronized(Student.class){

if(stu==null){

stu=new Student();

}

}

}

return stu;

}

04.测试类中使用

Student.getInstence()

 

 

posted @ 2018-01-15 11:10  默竹萱  阅读(96)  评论(0编辑  收藏  举报