您的位置:首页 > 编程语言 > Java开发

03-用私有构造器或者枚举类型强化 Singleton 属性

2017-01-24 20:51 381 查看
目录

方法一:公有静态成员,并且是 final 域

方法二:公有的成员是个静态工厂方法

上述两种方法都存在的问题

序列化预防“假冒”

方法三:单元素的枚举类型

1. 公有静态成员,并且是 final 域

public class Student {

public static final Student INSTANCE = new Student();

// 私有构造器
private Student() {

}

public void learnJava() {
System.out.println("effective java!");
}

// 主函数
public static void main(String[] args) {
Student mStudent = Student.INSTANCE;
mStudent.learnJava();
}
}


私有构造器仅被调用一次,用来实例化公有的静态final域Student.INSTANCE。由于缺少公有的或者受保护的构造器,所以保证了Student的全局唯一性。

2. 公有的成员是个静态工厂方法

public class Student {

private static final Student INSTANCE = new Student();

// 私有构造器
private Student() {

}

public static Student getInstance() {
return INSTANCE;
}

public void learnJava() {
System.out.println("effective java!");
}

// 主函数
public static void main(String[] args) {
Student mStudent = Student.getInstance();
mStudent.learnJava();
}
}


对于静态方法 Student.getInstance 的所有调用,都会返回同一个对象的引用,所以这保证了唯一性。

第1种,公有域方法的主要好处在于,组成类的成员的声明很清楚的表明了这个类是一个Singleton;但是相比之下不再比第2种方法有任何优势,因为现代 JVM 几乎都将静态工厂方法的调用内联化。

第2种,工厂方法的优势之一在于,它提供了灵活性,在不改变其API的前提下,可以改变该类是否应该为Singleton的想法;但是这种方法可以很容易的被修改成按不同需求返回相应的唯一实例。优势之二与泛型有关。其实相比之下,第一种方法更为简单。

3. 上述两种方法都存在的问题

享有特权的客户端可能借助AccessibleObject.setAccessible方法,通过反射机制调用私有构造器,这样就破坏了Singleton。如果要抵御这种攻击,可以修改构造器让它在被要求创建第二个实例的时候抛出异常。

下面代码对比:

public class Student {

private static final Student INSTANCE = new Student();

// 私有构造器
private Student() {

}

public static Student getInstance() {
return INSTANCE;
}

public void learnJava() {
System.out.println("effective java!");
}

// 主函数
public static void main(String[] args) {
//第一个
Student mStudent = Student.getInstance();
mStudent.learnJava();

//第二个
Student mStudent2 = Student.getInstance();
mStudent2.learnJava();

if(mStudent==mStudent2){
System.out.println("相同");
}else{
System.out.println("不相同");
}

//第三个
//通过类对象的getConstructor()或getDeclaredConstructor()方法获得构造器(Constructor)对象
//并调用其newInstance()方法创建对象,适用于无参和有参构造方法。
Constructor<?> constructor = Student.class.getDeclaredConstructors()[0];
//Student类中的成员变量为private,故必须进行此操作。
constructor.setAccessible(true);
try {
Student mStudent3 = (Student) constructor.newInstance();
mStudent3.learnJava();

if(mStudent==mStudent3){
System.out.println("相同");
}else{
System.out.println("不相同");
}
} catch (InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


修改构造器:

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Student {
private static int count = 0;
private static final Student INSTANCE = new Student();

// 私有构造器
private Student() {
if (count > 0) {
throw new IllegalArgumentException(
"Error,Cannot create Student twice!");
}
count++;
}

public static Student getInstance() {
return INSTANCE;
}

public void learnJava() {
System.out.println("effective java!");
}

// 主函数
public static void main(String[] args) {
// 第一个
Student mStudent = Student.getInstance();
mStudent.learnJava();

// 第二个
Student mStudent2 = Student.getInstance();
mStudent2.learnJava();

if (mStudent == mStudent2) {
System.out.println("相同");
} else {
System.out.println("不相同");
}

// 第三个
// 通过类对象的getConstructor()或getDeclaredConstructor()方法获得构造器(Constructor)对象
// 并调用其newInstance()方法创建对象,适用于无参和有参构造方法。
Constructor<?> constructor = Student.class.getDeclaredConstructors()[0];
// Student类中的成员变量为private,故必须进行此操作。
constructor.setAccessible(true);
try {
Student mStudent3 = (Student) constructor.newInstance();
mStudent3.learnJava();

if (mStudent == mStudent3) {
System.out.println("相同");
} else {
System.out.println("不相同");
}
} catch (InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


打印异常信息如下:

effective java!
effective java!
相同
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at ejava3.Student.main(Student.java:50)
Caused by: java.lang.IllegalArgumentException: Error,Cannot create Student twice!
at ejava3.Student.<init>(Student.java:13)
... 5 more


4. 序列化预防“假冒”

如果使用以上两种方法实现的 Singleton 类变成是可序列化的,仅仅加上 “implements Serializable” 是不够的。为了保证反序列化的时候,实例还是Singleton,必须声明所有的实例域都是瞬时(transient)的,并提供 readResolve 方法。否则,每次反序列化一个序列化的实例时,都会创建一个新的实例,比如在我们的例子中,会出现“假冒的 Student ”。

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Student implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private static int count = 0;
private static final Student INSTANCE = new Student();

// 私有构造器
private Student() {
if (count > 0) {
throw new IllegalArgumentException(
"Error,Cannot create Student twice!");
}
count++;
}

public static Student getInstance() {
return INSTANCE;
}

public void learnJava() {
System.out.println("effective java!");
}

// 主函数
public static void main(String[] args) throws FileNotFoundException,
IOException, ClassNotFoundException {
// 第一个
Student mStudent = Student.getInstance();
mStudent.learnJava();

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
"mStudent"));
oos.writeObject(mStudent);
oos.close();

ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
"mStudent"));
Student mStudent2 = (Student) ois.readObject();
ois.close();

if (mStudent == mStudent2) {
System.out.println("相同");
} else {
System.out.println("不相同");
}
}
}


打印信息:

effective java!
不相同


修改代码,在实现 Serializable 前提下,提供 readresolve 方法:

private Object readResolve() {
return INSTANCE;
}


打印结果就是“相同”啦,预防假冒,人人有责。

5. 单元素的枚举类型

public enum Student {
INSTANCE;

public void learnJava() {
System.out.println("effective java!");
}

// 主函数
public static void main(String[] args){
Student mStudent=Student.INSTANCE;
mStudent.learnJava();
}
}


这种方法在功能上和公共域方法相近,但是更加简洁,无偿提供序列化机制,绝对防止多次实例化。单元素的枚举类型成为实现singleton的最佳方法。

……
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐