单例模式
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.其他的方法