单例模式饿汉式
1,将构造器私有化
2,在类的内部直接创建对象(该对象是static)
3,提供一个公共的static方法
public class getinstance {
public static void main(String[] args) {
person instance = person.getInstance();
System.out.println(instance);
}
}
class person{
private String name;
private static person p = new person("张三");
private person(String name) {
this.name = name;
}
public static person getInstance(){
return p;
}
@Override
public String toString() {
return "person{" +
"name='" + name + '\'' +
'}';
}
}
单例模式懒汉式
1,构造器私有化
2,定义一个静态的属性
3,提供一个static公共方法,返回一个对象
public class getinstance1 {
public static void main(String[] args) {
person1 instance1 = person1.getInstance();
System.out.println(instance1);
}
}
class person1{
private String name;
private static person1 p1;
private person1(String name) {
this.name = name;
}
public static person1 getInstance(){
if (p1 == null){
p1 = new person1("李四");
}
return p1;
}
@Override
public String toString() {
return "person{" +
"name='" + name + '\'' +
'}';
}
}