单例模式

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

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

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

饿汉模式的两种:

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() {
		}
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值