单例设计模式懒汉式和恶汉式

一,单例设计模式懒汉式和恶汉式

懒汉式在类加载时不初始化,延迟加载。(配置文件)

饿汉式在类加载时初始化,加载慢,获取对象快。

饿汉式是线程安全的,

懒汉式需要加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

你可能感兴趣的:(设计模式,java,安全,deepin,opera)