博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
单例模式
阅读量:4100 次
发布时间:2019-05-25

本文共 2109 字,大约阅读时间需要 7 分钟。

单例模式:一个类只有一个实例方便控制并节约系统资源

优点:节省内存,加快访问速度,因此对象需要被公用的场合适合使用,如多个模块使用同一数据源连接对象等等

缺点:不适用于变化的对象,如果同一类型的对象总是在不同的用例场景发生变化,单例就会引起数据的错误,不能保存彼此的状态

饿汉模式的两种:

public class Singleton_hungry {	private final static Singleton_hungry singlen = new Singleton_hungry();	private Singleton_hungry() {}	public static Singleton_hungry  getInstance() {		return singlen;	}}class Singleton_hungry2{    private static Singleton_hungry2 instance;    static {        instance = new Singleton_hungry2();    }    private Singleton_hungry2() {}    public Singleton_hungry2 getInstance() {        return instance;    }}

懒汉的六种:

public class Singleton_lazy{	private static Singleton_lazy singleton= null;	private Singleton_lazy() {	}	public static Singleton_lazy getInstance() {		if(singleton==null) {			singleton = new Singleton_lazy();		}		return singleton;	}}class Singleton_lazy1{    private static Singleton_lazy1 singleton;    private Singleton_lazy1() {}    public static synchronized Singleton_lazy1 getInstance() {        if (singleton == null) {            singleton = new Singleton_lazy1();        }        return singleton;    }}class Singleton_lazy2{    private static Singleton_lazy2 singleton;    private Singleton_lazy2() {}    public static Singleton_lazy2 getInstance() {        if (singleton == null) {            synchronized (Singleton_lazy2.class) {                singleton = new Singleton_lazy2();            }        }        return singleton;    }}class Singleton_lazy3{	private static volatile Singleton_lazy3 singleton = null;	private Singleton_lazy3() {}	private static Singleton_lazy3 getInatance() {		if(singleton==null) {			synchronized(Singleton_lazy3.class) {				if(singleton==null) {					singleton = new Singleton_lazy3();				}			}		}		return singleton;	}}class Singleton_lazy4{	private Singleton_lazy4() {}	private static class SingletonInstance{		private static final Singleton_lazy4 singleton = new Singleton_lazy4();	}	public static Singleton_lazy4 getInstance() {		return SingletonInstance.singleton;	}}class Singleton_lazy5{	public enum singletonInstance{		singleton;		public void whatEverMethod() {		}	}}

 

转载地址:http://kgeii.baihongyu.com/

你可能感兴趣的文章
VS编译器运行后闪退,处理方法
查看>>
用div+css做下拉菜单,当鼠标移向2级菜单时,为什么1级菜单的a:hover背景色就不管用了?
查看>>
idea 有时提示找不到类或者符号
查看>>
JS遍历的多种方式
查看>>
ng-class的几种用法
查看>>
node入门demo-Ajax让前端angularjs/jquery与后台node.js交互,技术支持:mysql+html+angularjs/jquery
查看>>
神经网络--单层感知器
查看>>
注册表修改DOS的编码页为utf-8
查看>>
matplotlib.pyplot.plot()参数详解
查看>>
拉格朗日对偶问题详解
查看>>
MFC矩阵运算
查看>>
最小二乘法拟合:原理,python源码,C++源码
查看>>
ubuntu 安装mysql
查看>>
c# 计算器
查看>>
C# 简单的矩阵运算
查看>>
gcc 常用选项详解
查看>>
c++输入文件流ifstream用法详解
查看>>
c++输出文件流ofstream用法详解
查看>>
字符编码:ASCII,Unicode 和 UTF-8
查看>>
QT跨MinGW和MSVC两种编译器的解决办法
查看>>