jsp电商网站开发流程,织梦dedecms蓝色培训机构模板教育学校学院整站php网站源码,广州做门户网站,家乡网页设计教程1. 单例模式#xff0c;Singleton Pattern
1.1 Definition 定义
单例模式是确保类有且仅有一个实例的创建型模式#xff0c;其提供了获取类唯一实例#xff08;全局指针#xff09;的方法。 单例模式类提供了一种访问其唯一的对象的方式#xff0c;可以直接访问#xf…1. 单例模式Singleton Pattern
1.1 Definition 定义
单例模式是确保类有且仅有一个实例的创建型模式其提供了获取类唯一实例全局指针的方法。 单例模式类提供了一种访问其唯一的对象的方式可以直接访问而不需要实例化该类的对象。
1.2 Motivation 动机
Sometimes we want just a single instance of a class to exist in the system. For example, we want just one window manager, or just one factory for a family of products. 有时我们只希望系统中存在一个类的单个实例。例如我们只需要一个窗口管理器或者一个产品系列只需要一个工厂。
1.3 Benefit 益处
Controlled access to sole instance. 对唯一实例的受控访问More flexible than static class (class with all static properties and methods). 比静态类灵活 Static class must be stateless; Singleton could be stateful. 静态类必须无状态单例可以有状态
1.4 实现
私有构造方法获取唯一实例引用的静态方法
2. 单例模式类型
2.1 懒汉式-线程不安全
懒加载是线程安全否
public class LazyLoadingSingleton {private static LazyLoadingSingleton lazyLoadingSingleton;private LazyLoadingSingleton() {}public static LazyLoadingSingleton singleton() {if (lazyLoadingSingleton null) {lazyLoadingSingleton new LazyLoadingSingleton();}return lazyLoadingSingleton;}public void log(String msg) {System.out.println(Log: msg);}
}2.2 懒汉式-线程安全
懒加载是线程安全是优点首次调用初始化避免内存占用缺点影响效率
public class LazyLoadingSingleton {private static LazyLoadingSingleton singleton;private LazyLoadingSingleton() {}public static synchronized LazyLoadingSingleton singleton() {if (singleton null) {singleton new LazyLoadingSingleton();}return singleton;}public void log(String msg) {System.out.println(Log: msg);}
}
2.3 饿汉式
建议采用
懒加载否线程安全是优点未加锁效率高缺点类加载时初始化浪费内容
public class ClassLoadSingleton {private static ClassLoadSingleton singleton new ClassLoadSingleton();private ClassLoadSingleton() {}public static ClassLoadSingleton singleton() {return singleton;}public void log(String msg) {System.out.println(Log: msg);}
}解法静态内部类延迟类加载的对象实例化
public class ClassLoadSingleton {// private static ClassLoadSingleton singleton new ClassLoadSingleton();private static class SingleHandler {private static final ClassLoadSingleton singleton new ClassLoadSingleton();}private ClassLoadSingleton() {}public static ClassLoadSingleton singleton() {return SingleHandler.singleton;}public void log(String msg) {System.out.println(Log: msg);}
}
2.4 双重校验锁校验是否为空 双次校验是否为空类加锁在双次校验之中 可以使用 懒加载是线程安全是优点保证多线程下的效率
package singleton;public class DoubleCheckSingleton {private volatile static DoubleCheckSingleton singleton;private DoubleCheckSingleton() {}public static DoubleCheckSingleton singleton() {if (singleton null) {synchronized (DoubleCheckSingleton.class) {if (singleton null) {singleton new DoubleCheckSingleton();}}}return singleton;}public void log(String msg) {System.out.println(Log: msg);}
}
关于 volatile 易失性关键字 volatile 提醒编译器它后面所定义的变量随时都有可能改变因此编译后的程序每次需要存储或读取这个变量的时候都会直接从变量地址中读取数据。如果没有 volatile 关键字则编译器可能优化读取和存储可能暂时使用寄存器中的值在某一线程写入寄存器但且未写入变量地址如果这个变量由别的程序更新了的话将出现不一致的现象。