设计模式之单例模式
来源:互联网 发布:美工龙的教案 编辑:程序博客网 时间:2024/05/16 11:46
1. 2种实现方法,推荐使用简单的一种。
public class SingletonTest {/** * @param args */public static void main(String[] args) {Singleton1 singletonA = Singleton1.getSingleton1();Singleton1 singletonB = Singleton1.getSingleton1();System.out.println(singletonA == singletonB);//Singleton2 singletonC = Singleton2.getSingleton2();//Singleton2 singletonD = Singleton2.getSingleton2();//System.out.println(singletonC == singletonD);Singleton2 singletonE = Singleton2.getSingleton();Singleton2 singletonF = Singleton2.getSingleton();System.out.println(singletonE == singletonF);}}//单例模式的第一种实现class Singleton1{//静态成员变量,类加载时候new出来了。private static Singleton1 singleton = new Singleton1();//必须new出来,不能设置为空,不然多线程时候出问题。//私有构造函数private Singleton1(){}public static Singleton1 getSingleton1(){return singleton;}}//第二种实现class Singleton2{private static Singleton2 singleton;private Singleton2(){}public static Singleton2 getSingleton2(){//必须判断,加锁if(singleton == null){synchronized (Singleton2.class) {if(singleton == null){singleton = new Singleton2();}}}return singleton;}//另一种同步方式public static synchronized Singleton2 getSingleton(){if(singleton == null){singleton = new Singleton2();}return singleton;}}
- 设计模式之 单例设计模式
- 设计模式之 单例设计模式
- 设计模式之单例设计模式
- 设计模式之-----------单例设计模式
- 设计模式之:单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之-单例设计模式
- 设计模式之单例设计模式 标签: 设计模式
- 设计模式之单例
- 设计模式之单例
- 设计模式之 单例
- Android开发开源源代码
- .NET FrameWork 各版本程序的兼容测试
- 第十一次实验报告
- webConfig对访问者的权限设置
- Linux内核设计的艺术:图解Linux操作系统架构设计与实现原理
- 设计模式之单例模式
- svn
- 第十一次上机实验
- You're Gonna Go Far, Kid
- 新手易学——新手学淘宝开店
- 从普通IT民工到盗版软件大王
- 黑马程序员《.NET 方法》
- 深入理解Java虚拟机:JVM高级特性与最佳实践
- 目标检测(Object Detection)原理与实现(三)