单例设计模式懒汉式和恶汉式
一,单例设计模式懒汉式和恶汉式
懒汉式在类加载时不初始化,延迟加载。(配置文件)
饿汉式在类加载时初始化,加载慢,获取对象快。
饿汉式是线程安全的,
懒汉式需要加synchronized,否则不安全。
二,饿汉式
1 public class Singletonehan { 2 private static Singletonehan singleton=new Singletonehan(); 3 private Singletonehan() { 4 } 5 public static Singletonehan getInstance(){ 6 return singleton; 7 } 8 9 @Override 10 public String toString() { 11 return "Singletonehan{}"; 12 } 13 }
测试
1 public class testehan { 2 public static void main(String[] args) { 3 Singletonehan singletonehan = Singletonehan.getInstance(); 4 System.out.println(singletonehan); 5 } 6 }
三,懒汉式
1 public class Singletonlanhan { 2 // private static Singletonlanhan singleton=new Singletonlanhan(); 3 private static Singletonlanhan singleton=null; 4 5 private Singletonlanhan() { 6 } 7 8 public static Singletonlanhan getInstance() { 9 if (singleton == null) { 10 singleton = new Singletonlanhan(); 11 } 12 return singleton; 13 } 14 15 @Override 16 public String toString() { 17 return "Singletonlanhan{}"; 18 } 19 }
测试
1 public class test { 2 public static void main(String[] args) { 3 Singletonlanhan singletonlanhan = Singletonlanhan.getInstance(); 4 System.out.println(singletonlanhan); 5 } 6 }
结果
Singletonlanhan{}
Process finished with exit code 0
补充加synchronized后的懒汉
1 public class Singletonlanhan { 2 // private static Singletonlanhan singleton=new Singletonlanhan(); 3 private static Singletonlanhan singleton=null; 4 5 private Singletonlanhan() { 6 } 7 8 public synchronized static Singletonlanhan getInstance() { 9 if (singleton == null) { 10 singleton = new Singletonlanhan(); 11 } 12 return singleton; 13 } 14 15 @Override 16 public String toString() { 17 return "锁Singletonlanhan{}"; 18 } 19 }
结果
锁Singletonlanhan{}
Process finished with exit code 0
当一个男人不再对你啰嗦,不再缠着你,不再没事找你,对你说话也客气了,也不再气你了。那么恭喜你,你已经成功的失去了他。别嫌弃男人幼稚,那是他喜欢你,爱你。女人说男人像小孩子一样不成熟,可又有谁知道,男人在自己喜欢的女人面前才像小孩子,如果不喜欢你了,不爱你了,他比你爸还成熟。