单例模式-恶汉式,懒汉式
单例模式适用于创建对象消耗大量资源,所以只创建一个对象
懒汉和恶汉的区别,什么时候new对象
恶汉式:
先创建
public class lazy {
private lazy(){
}
private static lazy l1 = null;//刚开始不创建
public static lazy getLazy(){
String s = "";
if(l1 == null){//判断有没有被创建
s = "创建懒汉1";
l1 = new lazy();
}
System.out.println(s);
return l1;
}
}
public class main {
public static void main(String[] args) {
lazy l1 = lazy.getLazy();
lazy l2 = lazy.getLazy();
lazy l3 = lazy.getLazy();
}
————————————————————————————
懒汉式:
最开始不创建对象,直到有人调用了再创建,之后的人都使用这个对象
public class lazy {
private lazy(){
}
private static lazy lazy = null;//刚开始不创建
public static lazy getLazy(){
if(lazy == null){//判断有没有被创建
lazy = new lazy();
}
return lazy;
}
}
枚举
//每个枚举都是单例的
public class enum1 {
public static void main(String[] args) {
Car c =Car.AUDI;//调用该构造方法
Car c1 =Car.AUDI;
Car c2 =Car.BENZ;
c.change("奥迪双钻");//当这里改变参数后,new一个相同类的的对象这个值也改变了
c.showInfo();
c1.showInfo();
c2.showInfo();
System.out.println(c.equals(c1));//true
System.out.println(c1.equals(c2));
}
}
enum Car{
BENZ("奔驰","BENZ"),//调用私有构造方法
BMW("宝马","BMW"),
AUDI("奥迪","AUDI");
private final String name;
private String n;
private Car(String name ,String n){//构造方法
this.name = name;
this.n = n;
}
public void change(String n){
this.n = n;
}
public void showInfo(){
System.out.println(n+":"+name);
}
}
网友评论