码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-06-29 13:02:14      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:class   单例设计   ret   out   饿汉   单例设计模式   err   code   sys   

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

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

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

饿汉式是线程安全的,

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

 

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

标签:class   单例设计   ret   out   饿汉   单例设计模式   err   code   sys   

原文地址:https://www.cnblogs.com/fengtangjiang/p/11106102.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!