
核心点:
—— 单例类只有一个实例对象;
—— 该单例对象必须由单例类自行创建;
—— 单例类对外提供一个访问该单例的全局访问点;
实现方式:
1.构造方法私有
2.提供类自身定义一个静态私有实例
3.向外提供一个静态的公有方法用于创建或获取该静态私有实例,该方法是对外唯一提供的创建实例途径。
主要分类:
——饿汉式:类一旦加载就创建实例,保证在调用静态方法之前单例已经存在了,特点是线程安全。
——懒汉式:只有在第一次调用的时候才会创建,非线程安全,需要考虑线程同步。
package net.mosang.singleton;
public class HungrySingLeton {
private static HungrySingLeton instance = new HungrySingLeton();
private HungrySingLeton() {//私有构造方法
public static HungrySingLeton getInstance() { //对外提供唯一的获取实例方法
package net.mosang.singleton;
/**
* 饿汉式单例模式
* @author heiry
*
*/
public class HungrySingLeton {
private static HungrySingLeton instance = new HungrySingLeton();
private HungrySingLeton() {//私有构造方法
}
public static HungrySingLeton getInstance() { //对外提供唯一的获取实例方法
return instance;
}
}
package net.mosang.singleton;
/**
* 饿汉式单例模式
* @author heiry
*
*/
public class HungrySingLeton {
private static HungrySingLeton instance = new HungrySingLeton();
private HungrySingLeton() {//私有构造方法
}
public static HungrySingLeton getInstance() { //对外提供唯一的获取实例方法
return instance;
}
}
package net.mosang.singleton;
public class LazySingLeton {
private static LazySingLeton instance =null;
private LazySingLeton() {//私有构造方法
public static synchronized LazySingLeton getInstance() { //synchronized线程同步,避免并发创建多个对象
instance = new LazySingLeton();
package net.mosang.singleton;
/**
* 懒汉式单例模式
* @author heiry
*
*/
public class LazySingLeton {
private static LazySingLeton instance =null;
private LazySingLeton() {//私有构造方法
}
public static synchronized LazySingLeton getInstance() { //synchronized线程同步,避免并发创建多个对象
if(instance==null) {
instance = new LazySingLeton();
}
return instance;
}
}
package net.mosang.singleton;
/**
* 懒汉式单例模式
* @author heiry
*
*/
public class LazySingLeton {
private static LazySingLeton instance =null;
private LazySingLeton() {//私有构造方法
}
public static synchronized LazySingLeton getInstance() { //synchronized线程同步,避免并发创建多个对象
if(instance==null) {
instance = new LazySingLeton();
}
return instance;
}
}