关于Java设计模式之单例设计模式

什么是单例设计模式?

确保系统中一个类只产生一个实例。

单例设计模式的好处:

1)频繁使用的对象,可以省略创建对象所花费的时间

2)由于不需要new,节省系统资源。对系统内存的使用频率降低,将减轻回收的压力。

 

饿汉式与懒汉式:

1)懒汉式是延时加载,他是在需要的时候才创建对象,

2)饿汉式在加载类的时候就会创建,

懒汉式:

 1 public class Singleton {
 2     //懒汉式:
 3     private static Singleton singleton = null; //有一个关于自己的引用;
 4     //私有无参构造函数;
 5     private Singleton() {
 6         
 7     }
 8     //可能存在多个类同时使用该类 故设为同步方法 
 9     public static synchronized Singleton getSingleton() {
10         if(singleton==null) {
11             //保证只有一个该类的对象
12             singleton=new Singleton();
13         }
14         return singleton;
15     }
16     public void test() {
17         System.out.println("单例设计模式被调用");
18     }
19 }

 

懒汉式测试:

1 public class SingletonTest {
2     
3     public static void main(String[] args) {
4         //Singleton singleton = new Singleton();直接new 引用就会报错
5         Singleton.getSingleton().test();
6         //就会创建该类的对象
7     }
8 }

饿汉式:

 1 public class Singleton {
 2     //饿汉式:
 3     private static Singleton singleton = new Singleton(); //有一个关于自己的引用;
 4     //私有无参构造函数;
 5     private Singleton() {
 6         
 7     }
 8    
 9     public static Singleton getSingleton() {
10         return singleton;
11     }
12     public void test() {
13         System.out.println("单例设计模式被调用");
14     }
15 }

 

posted @ 2018-01-31 16:03  游园复梦  阅读(125)  评论(0编辑  收藏  举报