Android设计模式(1)----单例模式

本文介绍了单例模式的基本概念及其两种实现方式:饱汉式和饿汉式。此外还讨论了如何根据具体需求调整单例模式,包括传递额外参数和确保线程安全。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在很多设计模式中,我相信大多数程序猿最早接触的设计模式就是单例模式啦,当然了我也不例外。单例模式应用起来应该是所有设计模式中最简单的。单例模式虽然简单,但是如果你去深深探究单例模式,会涉及到很多很多知识,我会继续更新这篇文章的。单例模式在整个系统中就提供了一个对象,然后整个系统都去使用这一个对象,这就是单例的目的。

一、饱汉式单例:

[html]  view plain  copy
  1. public class Singleton {      
  2.         /**    
  3.          * 单例对象实例    
  4.          */      
  5.         private static Singleton instance = null;      
  6.         public static Singleton getInstance() {      
  7.             if (instance == null) {                       
  8.                 instance = new Singleton();             
  9.             }      
  10.             return instance;      
  11.         }      
  12.     }  

二、饿汉式单例:

[html]  view plain  copy
  1. public class Singleton {      
  2.             /**    
  3.              * 单例对象实例    
  4.              */      
  5.             private static Singleton instance = new Singleton();      
  6.                
  7.            public static Singleton getInstance() {      
  8.                 return instance;      
  9.             }      
  10.         }  

这两种单例在实际的代码中,往往是不能满足要求的,这就需要我们根据自己的需求来改写这些单例模式,

例如:如果创建的单例对象需要其他参数,这个时候,我们就需要这样改写:

[html]  view plain  copy
  1. public class Singleton {      
  2.             /**    
  3.              * 单例对象实例    
  4.              */      
  5.             private static Singleton instance = null;      
  6.                
  7.            public static Singleton  getInstance(Context context) {    
  8.                 if (instance == null) {    
  9.                     instance = new Singleton(context);    
  10.                 }    
  11.             return instance;    
  12.         }  
  13.     }  

例如: 资源共享情况下,必须满足多线程的并发访问,这个时候,我们就应该这么做:

[html]  view plain  copy
  1. public class Singleton {      
  2.             /**    
  3.              * 单例对象实例    
  4.              */      
  5.             private static Singleton instance = null;      
  6.                
  7.             public synchronized static Singleton getInstance() {      
  8.                 if (instance == null) {      
  9.                     instance = new Singleton();      
  10.                 }      
  11.                 return instance;      
  12.             }      
  13.     }  

其实无论什么条件下,无论怎么改变,都是这两种单例模式的变种!!!!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值