java单例模式
单例模式单例模式是一种常见的设计模式,
单例模式分三种:懒汉式单例、饿汉式单例、登记式单例三种。
单例模式有一下特点:
1、单例类只能有一个实例。
2、单例类必须自己自己创建自己的唯一实例。
3、单例类必须给所有其他对象提供这一实例。
一、懒汉式单例在类被加载的时候,唯一实例已经被创建。这个设计模式在Java中容易实现,在别的语言中难以实现。
单例模式-懒汉式单例
public class LazySingleton {
/*** 私有静态对象,加载时候不做初始化 */
private static LazySingleton m_intance=null;
/*** 私有构造方法,避免外部创建实例 */
private LazySingleton(){}
/*** 静态工厂方法,返回此类的唯一实例.* 当发现实例没有初始化的时候,才初始化. * @return LazySingleton */
synchronized public static LazySingleton getInstance(){
if(m_intance==null){
m_intance=new LazySingleton();
}
return m_intance;
}
}
//测试一下单例模式
LazySingleton lazySingleton = LazySingleton.getInstance();
LazySingleton lazySingleton1 = LazySingleton.getInstance();
if(lazySingleton==lazySingleton1)){
System.out.println("同一个对象实例");
}else{
System.out.println("不是同一个对象实例");
}
二、饿汉式单例在类加载的时候不创建单例实例。只有在第一次请求实例的时候的时候创建,并且只在第一次创建后,以后不再创建该类的实例。
/***单例模式-饿汉式单例*/
public class EagerSingleton {
/**私有的(private)唯一(static final)实例成员,在类加载的时候就创建好了单例对象*/
private static final EagerSingleton m_instance = new EagerSingleton();
/*** 私有构造方法,避免外部创建实例 */
private EagerSingleton() {} //提供了一个空的构造方法
/*** 静态工厂方法,返回此类的唯一实例.* @return EagerSingleton */
public static EagerSingleton getInstance() {
return m_instance;
}
}
//下面来判断一下有没有达到单例效果(系统运行的时候只出来一个空例)
EagerSingleton eagerSingleton = EagerSingleton.getInstance();
EagerSingleton eagerSingleton1 = EagerSingle
相关文档:
经过了一周的努力,成功签下了上海宝信软件西安分公司。
在这里,简单分享一下这次的经历。
首先简单陈述下个人的一些基本信息,正规统招本科非计算机专业,2008-2009年8月接受东方标准软件工程师培训,完成了一些比较完整的项目,掌握了基本的J2EE开发的核心技术。培训结束了,参加了一些知名企业的校园 ......
Windows->Preference->Java->Code Style->Code Templates->Code->New Java file->Edit
原来的模板:
${filecomment}
${package_declaration}
${typecomment}
${type_declaration}
修改后:
${filecomment}
${package_declaration}
/**
* @author Xing,Ming
* @version ${date} ${time}
* ......
EJB: Enterprise JavaBeans 企业JavaBean组件
IDL: Interface Definition Language 接口定义语言
J2EE CA:J2EE Connector Architecture J2EE 连接器架构
JAAS : The Java Authenticat ......