单例模式
2016-07-26 20:32
363 查看
饿汉式单例
懒汉式单例
Java code?
public class Singleton { private static Singleton singleton = new Singleton(); private Singleton(){} public static Singleton getInstance(){ return singleton; } }
懒汉式单例
public class Singleton { private static Singleton singleton; private Singleton(){} public static synchronized Singleton getInstance(){ if(singleton==null){ singleton = new Singleton(); } return singleton; } }
Java code?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | package com; /** * <p> * Title: * </p> * * <p> * Description: * </p> * * <p> * Copyright: 转载请注明出处http://blog.csdn.net/sunyujia/ * </p> * * @author 孙钰佳 * @main sunyujia@yahoo.cn * @date Oct 5, 2008 6:07:40 PM */ public class Test { static { System.out.println( "我是用来做测试的,传统的单例模式会在这个时机被实例化" ); } public static Test getInstance() { return TestInstance.getInstance(); } private Test() { System.out.println( "oh! test" ); } private static class TestInstance { private static Test instance = new Test(); private TestInstance() { } private static Test getInstance() { return instance; } }; public static void main(String[] args) { System.out.println(Test. class ); System.out.println( "========================" ); System.out.println(Test.getInstance()); } } |
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序