Java 单例设计模式

Singleton:单例模式安全

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

2.这个实例对象只能经过本类中建立=====>私有化构造测试

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

实现单例的3种模式:线程

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

建立懒汉单例模式的步骤:接口

01.建立静态变量get

private static Student stu;class

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()

相关文章
相关标签/搜索