黑马程序员--java 单例设计模式

来源:互联网 发布:java编程思想视频全集 编辑:程序博客网 时间:2024/05/29 18:47
<div><span style="font-family:Arial;font-size:14px;color:#333333;line-height: 26px;">单例设计模式解决的问题:保证一个类在内存中的对象唯一性。</span><br style="color: rgb(51, 51, 51); line-height: 26px; font-family: Arial; font-size: 14px;" /><span style="font-family:Arial;font-size:14px;color:#333333;line-height: 26px;">比如:多程序读取一个配置文件时,建议配置文件封装成对象会方便操作其中数据。但需要保证多个程序读到的是同一个配置文件对象,该配置文件对象在内存中是唯一的。</span></div><div><span style="font-family:Arial;font-size:14px;color:#333333;line-height: 26px;">如何保证对象唯一性呢?</span><br style="color: rgb(51, 51, 51); line-height: 26px; font-family: Arial; font-size: 14px;" /><span style="font-family:Arial;font-size:14px;color:#333333;line-height: 26px;">思想以及步骤:</span><br style="color: rgb(51, 51, 51); line-height: 26px; font-family: Arial; font-size: 14px;" /><span style="font-family:Arial;font-size:14px;color:#333333;line-height: 26px;">1,不让其他程序创建该类对象。>>></span><span style="font-family:Arial;font-size:14px;color:#ff00;line-height: 26px;">◆私有化构造函数;</span><br style="color: rgb(51, 51, 51); line-height: 26px; font-family: Arial; font-size: 14px;" /><span style="font-family:Arial;font-size:14px;color:#333333;line-height: 26px;">2,在本类中创建一个本类对象。 >>></span><span style="font-family:Arial;font-size:14px;color:#ff00;line-height: 26px;">◆私有并静态的本类对象;</span><br style="color: rgb(51, 51, 51); line-height: 26px; font-family: Arial; font-size: 14px;" /><span style="font-family:Arial;font-size:14px;color:#333333;line-height: 26px;">3,对外提供方法,让其他程序可以获取这个对象。 >>></span><span style="font-family:Arial;font-size:14px;color:#ff00;line-height: 26px;">◆定义公有并静态的方法,返回该对象。</span></div>
 <pre class="java" name="code">class Single{private Single(){} //私有化构造函数,不让其他程序创建该类实例。   private static Single s = new Single(); //创建私有并静态的本类对象。   public static Single getInstance()  //定义公有并静态的方法,返回该对象。{        return s;      }  }   class Testt{  public static void main(String[] args){     Single s1 = Single.getInstance();       Single s2 = Single.getInstance();       System.out.println(s1==s2);//验证两个对象时不是同一个?true,   }  }

                                             
0 0