java设计模式
Posted 吴浩2008
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java设计模式相关的知识,希望对你有一定的参考价值。
1、单例模式
- 饿汉模式
public class Singleton { private static final Singleton INSTANCE = new Singleton(); // Private constructor suppresses // default public constructor private Singleton() {}; public static Singleton getInstance() { return INSTANCE; } }
- 懒汉模式
public class Singleton { private static volatile Singleton INSTANCE = null; // Private constructor suppresses // default public constructor private Singleton() {}; //Thread safe and performance promote public static Singleton getInstance() { if(INSTANCE == null){ synchronized(Singleton.class){ // When more than two threads run into the first null check same time, // to avoid instanced more than one time, it needs to be checked again. if(INSTANCE == null){ INSTANCE = new Singleton(); } } } return INSTANCE; } }
以上是关于java设计模式的主要内容,如果未能解决你的问题,请参考以下文章