单例模式

单例模式
1.1解决问题:一个类永远都只能创建出一个对象
例如:
(1)地球:唯一的对象
(2)池:连接池,线程池
单例:单个实例-单个对象 singleton
1.2实现的过程
a.类:依然是类
b.属性:其他的属性
当前类的静态属性-private
(a):懒汉模式:没有初始化

public class Earth {
	private String name;
	private int count;
	// (1).当前类的镜头属性(保存一个唯一的对象)懒汉
	private static Earth earth;

	// (2).构造私有化:封住系统自动提供的默认构造
	private Earth() {
	}
	// (3).声明一个镜头的返回当前对象的方法:构建对象的方法
	public static Earth getInstance() {
		if (earth == null) {
			earth = new Earth();
		}
		return earth;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
	@Override
	public String toString() {
		return "Earth [name=" + name + ", count=" + count + "]";
	}
}

(b):饿汉模式:初始化

public class Earth_Hugry {
	private String name;
	private int count;
	// (1).当前类的镜头属性(保存一个唯一的对象)饿汉
	private static Earth_Hugry earth = new Earth_Hugry();

	// (2).构造私有化:封住系统自动提供的默认构造
	private Earth_Hugry() {
	}
	// (3).声明一个镜头的返回当前对象的方法:构建对象的方法
	public static Earth_Hugry getInstance() {
		return earth;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
	@Override
	public String toString() {
		return "Earth [name=" + name + ", count=" + count + "]";
	}
}

构建地球对象
Earth earth=Earth.getInstance();
c.构造方法 private:阻止了用户随意new对象
d.一个返回当前对象的静态方法 getInstance()
e.其他的方法

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值