/**
* 单利模式
*/
public class Test1 {
/**
* 这里的标识符 和下面的实体类注意顺序
* 如果new在前面 设置变量在后面变量还没有被初始化造成错误
*/
private static boolean isNew1=true;
private static Test1 t1=new Test1();
// 构造方法是私有的
private Test1(){
if(isNew1){
isNew1 = !isNew1;
}
else{
throw new RuntimeException("单利防止侵犯");
}
}
public static Test1 getTest(){
return t1;
}
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
Test1 t1=Test1.getTest();
Test1 t2=Test1.class.newInstance();
System.out.println(t1.hashCode());
System.out.println(t2.hashCode());
}
}
转载于:https://my.oschina.net/findurl/blog/1832050