脚本宝典收集整理的这篇文章主要介绍了初探设计模式:单例模式,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
public class SingletonLazy {
/**
* 创建当前类私有化实例对象
*/
PRivate static SingletonLazy instance;
/**
* 设置构造函数私有化,使当前类不能被实例化
*/
private SingletonLazy(){}
/**
* 获取唯一可用对象
* 加锁synchronized 保证单例
* @return
*/
public static synchronized SingletonLazy getInstance() {
if (instance == null) {
instance = new SingletonLazy();
}
return instance;
}
/**
* 内置方法
*/
public void showMessage(){
System.out.println("Hello World!");
}
}
public class SingletonHungry {
/**
* 创建当前类私有化实例对象
*/
private static SingletonHungry instance = new SingletonHungry();
/**
* 设置构造函数私有化,使当前类不能被实例化
*/
private SingletonHungry() {}
/**
* 获取唯一可用对象
* @return
*/
public static SingletonHungry getInstance() {
return instance;
}
/**
* 内置方法
*/
public void showMessage(){
System.out.println("Hello World!");
}
}
public class SingletonLocking {
/**
* 创建当前类私有化实例对象
*/
private volatile static SingletonLocking instance;
/**
* 设置构造函数私有化,使当前类不能被实例化
*/
private SingletonLocking() {}
/**
* 获取唯一可用对象
* @return
*/
public static SingletonLocking getInstance() {
if (instance == null) {
synchronized (SingletonLocking.class) {
if (instance == null) {
instance = new SingletonLocking();
}
}
}
return instance;
}
/**
* 内置方法
*/
public void showMessage(){
System.out.println("Hello World!");
}
}
public class SingletonInner {
private static class SingletonHolder {
private static final SingletonInner INSTANCE = new SingletonInner();
}
/**
* 设置构造函数私有化,使当前类不能被实例化
*/
private SingletonInner() {}
/**
* 获取唯一可用对象
* @return
*/
public static final SingletonInner getInstance() {
return SingletonHolder.INSTANCE;
}
/**
* 内置方法
*/
public void showMessage(){
System.out.println("Hello World!");
}
}
public enum ENUM_SINGLETON {
/**
* 实例
*/
INSTANCE;
/**
* 内置方法
*/
public void showMessage(){
System.out.println("Hello World!");
}
}
public class SingletonClient {
public static void main(String[] args) {
// 懒汉式
lazy();
// 饿汉式
hungry();
// 双重校验锁
doubleCheck();
// 静态内部类
inner();
// 枚举
enums();
}
/**
* 懒汉式
*/
public static void lazy() {
// 编译时错误,无法通过此种方式实例化
//SingletonLazy instance = new SingletonLazy();
// 获取唯一可用对象
SingletonLazy instance = SingletonLazy.getInstance();
instance.showMessage();
}
/**
* 饿汉式
*/
public static void hungry() {
// 获取唯一可用对象
SingletonHungry instance = SingletonHungry.getInstance();
instance.showMessage();
}
/**
* 双重校验锁
*/
public static void doubleCheck() {
// 获取唯一可用对象
SingletonLocking instance = SingletonLocking.getInstance();
instance.showMessage();
}
/**
* 静态内部类
*/
public static void inner() {
// 获取唯一可用对象
SingletonInner instance = SingletonInner.getInstance();
instance.showMessage();
}
/**
* 枚举
*/
public static void enums() {
ENUM_SINGLETON.INSTANCE.showMessage();
}
}
以上是脚本宝典为你收集整理的初探设计模式:单例模式全部内容,希望文章能够帮你解决初探设计模式:单例模式所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。