设计模式-最简单的设计模式 单例模式

单例模式:是最简单的设计模式

作用:就是保证在整个应用程序的生命周期中, 任何一个时刻,单例类的实例都只存在一个。

分为两种饿汉模式和懒汉模式

饿汉模式 :当类加载时比较慢 但是呢 获取对象快

public class Singleton {
//把构造函数私有化的作用是 不允许在其他类中用new的方式创建 Singleton 的实例
private Singleton() {
}
//这个保证了在全局中只能有一个实例
private static Singleton singleton = new Singleton();
//这个是进行了封装
public static Singleton getSingleton() {
return singleton;
}

}

懒汉模式:当类加载时比较快 但是呢 获取对象较慢

public class Singleton {
//把构造函数私有化的作用是 不允许在其他类中用new的方式创建 Singleton 的实例
private Singleton() {
}
private static Singleton singleton ;
//这个是进行了封装 这个保证了在全局中只能有一个实例
public static Singleton getSingleton() {
if (singleton==null) {
singleton = new Singleton();
}
return singleton;
}

}

 

posted @ 2015-04-24 18:03  旅人-  阅读(108)  评论(0编辑  收藏  举报
=================================================================================================== 喜欢程序员这种每天都充实的感觉。