策略模式之单例模式

将类的构造器私有化,然后提供一个返回值,供其他类实例化对象,这样实例化的对象就只能有一个对象。一个类,一个 JVM 中,就只有一个实例存在。

大体思路:

  1. 将构造器私有化;
  2. 将提供的调用的静态值指向实例;
  3. 返回静态属性

代码:通过将 Earth 类的构造器私有化,其他类就不能访问这个构造器,只能通过 Earth 类中自己提供的变量或者方法调用,这样其他类在实例化 Earth 类的时候,实例化的对象就只能是一个。

public class Earth {
	String name;
	int year;
	private Earth() {}
	public static Earth earth = new Earth();
}
public class test1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Earth e1 = Earth.earth;
		Earth e2 = Earth.earth;
		System.out.println(e1==e2);
	}

}

上面的属于 饿汉式 单利模式,无论是否被调用,都会被加载,而 懒汉式 只是需要的时候才进行加载,下面是 懒汉式  的单例模式。

public class Earth {
	String name;
	int year;
	private Earth() {}
	public static Earth earth;
	public static Earth getEarth() {
		if(earth == null) {
			earth = new Earth();
		}
		return earth;
	}
}
public class test1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Earth e1 = Earth.earth;
		Earth e2 = Earth.getEarth();
		System.out.println(e1==e2);
	}

}

上面的例子输出 false,因为懒汉式的只是需要的时候才加载,如果将 e1 改成和 e2 一样的话,则会输出 true。

如果业务有比较充分的启动时间和加载时间就使用 饿汉模式,否则的话就使用 懒汉模式.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值