单例模式(饿汉式&懒汉式)

单例模式的特点:解决了一个类在内存的唯一性,这个类的对象只有一个。

写单例模式的步骤:

1. 私有修饰构造方法

2. 在本类的成员位置, new 自己类的对象

3. 提供一个静态方法,返回本类的对象

A: 恶汉式

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package demo01;
/**
  * 单例设计模式恶汉式
  * @author Administrator
  *
  */
public class SingleDesignModel1 {
     //私有构造方法
     private SingleDesignModel1(){
     }
     //在自己的成员变量的位置,new 自己
     private static final SingleDesignModel1 singleDesignModel1= new SingleDesignModel1();
     //提供一个静态方法,返回一个本类对象
     public static SingleDesignModel1 getInstance(){
         return singleDesignModel1;
     }
}

B:懒汉式

 

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package demo01;
/**
  * 单例模式的懒汉式
  * @author Administrator
  *
  */
public class SingleDesignModel2 {
     private static SingleDesignModel2 singleDesignModel2= null ;
     private SingleDesignModel2(){
         
     }
     public static SingleDesignModel2 getInstance(){
         if (singleDesignModel2== null ){
             singleDesignModel2= new SingleDesignModel2();
         }
         return singleDesignModel2;
     }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值