单例模式

public class DesingeDemo {
static class SingleTon {
// 饱汉模式
private static SingleTon singleton;


private SingleTon() {
}


public static SingleTon getSingleTon() {
singleton = new SingleTon();
return singleton;
}
//二汉模式
/* private static SingleTon singleton2 = new SingleTon();


private static SingleTon getSIngSingleTon() {
return singleton;
}
*/
}


public static void main(String[] args) {
/* SingleTon st = new SingleTon();
SingleTon st2 = new SingleTon();
st = SingleTon.getSingleTon();
st = SingleTon.getSingleTon();
System.out.println(st.hashCode());

System.out.println(st.hashCode());*/

package com.test;


public class Singleton {
// 恶汉单例模式,不管是否使用会有一个实例存在于内存中
/*
* private static Singleton singleton = new Singleton();

* private Singleton() { }

* public static Singleton getinSingleton() { return singleton; }
*/
// 懒汉单例模式,但是多线程下面可能会出现问题
/*
* private static Singleton singleton; private Singleton() { } public static
* synchronized Singleton getSingleton() { if (singleton == null) {
* singleton = new Singleton(); } return singleton; }
*/
/*
* private static Singleton singleton; private Singleton(){

* } public static synchronized Singleton getsingleton(){
* if(singleton==null){ singleton=new Singleton(); } return singleton; }
*/


private Singleton() {


}


/* private static Singleton singleton; */
private static class Inner {
private static Singleton isnSingleton = new Singleton();
}


private static Singleton getSingleton() {
return Inner.isnSingleton;
}
/*
* private Singleton(){

* } private static class Inner{ private static Singleton instant=new
* Singleton(); } public static Singleton getInstance(){ return
* Inner.instant; }
*/


}

阅读更多
换一批

没有更多推荐了,返回首页