GOF(gang of four,四人帮)
问题常见,专家级的解决方案。
23种设计模式。
单例模式:singleton,某个类在运行期间有且只有一个对象。
1.懒汉式
public class GarbageBox {
private static GarbageBox instance = new GarbageBox();
/**
* 静态成员
*/
public static GarbageBox getInstance(){
// if(instance == null){
// instance = new GarbageBox();
// }
return instance ;
}
/**
* 构造私有
*/
private GarbageBox(){
}
}
问题常见,专家级的解决方案。
23种设计模式。
单例模式:singleton,某个类在运行期间有且只有一个对象。
1.懒汉式
//多线程访问存在实例化多个对象的风险.
package java.thread;
/**
* 回收站
*/
public class GarbageBox {
private static GarbageBox instance ;
/**
* 静态成员
*/
public static GarbageBox getInstance(){
if(instance != null){
return instance ;
}
//
synchronized (GarbageBox.class){
if(instance == null){
instance = new GarbageBox();
}
return instance ;
}
}
/**
* 构造私有
*/
private GarbageBox(){
}
}
package java.thread;
/**
* Created by Administrator on 2017/7/27.
*/
public class SingletonDemo {
public static void main(String[] args) {
//匿名内部类对象
new Thread(){
public void run() {
GarbageBox box = GarbageBox.getInstance();
System.out.println(box);
}
}.start();
new Thread(){
public void run() {
GarbageBox box = GarbageBox.getInstance();
System.out.println(box);
}
}.start();
}
}
public class GarbageBox {
private static GarbageBox instance = new GarbageBox();
/**
* 静态成员
*/
public static GarbageBox getInstance(){
// if(instance == null){
// instance = new GarbageBox();
// }
return instance ;
}
/**
* 构造私有
*/
private GarbageBox(){
}
}