Java基础之单例模式

Linux大全评论318 views阅读模式

这里主要讲一下单例模式的两种形式,当然还有其他的实现方式

单例模式的作用主要是确保在Java应用中,一个类只用一个实例存在

主要方法是定义一个类,他的构造方法是private的,他的方法都是static的

形式一

在自己的内部定义并实例化一个自己的实例,getInstance()方法是供外部访问本类使用的,可以直接访问。

  1. /** 
  2.  * 单例模式一 
  3.  * 一般认为这种形式更安全一些  
  4.  */  
  5. public class Singleton {  
  6.       
  7.     private Singleton(){}  
  8.     private static Singleton instance = new Singleton();  
  9.     private static Singleton getInstance(){  
  10.         return instance;  
  11.     }  
  12. }  
  1. /** 
  2.  * 单例模式二 
  3.  */  
  4. public class Singleton2 {  
  5.     private static Singleton2 instance = null;  
  6.     private static synchronized Singleton2 getInstance(){  
  7.         if(instance == null){  
  8.             instance = new Singleton2();  
  9.         }  
  10.         return instance;  
  11.     }  
  12. }  

企鹅博客
  • 本文由 发表于 2019年9月6日 22:39:44
  • 转载请务必保留本文链接:https://www.qieseo.com/172000.html

发表评论