單例程 餓漢式 懶漢式
阿新 • • 發佈:2019-01-22
<strong></strong><pre name="code" class="java"><strong>【餓漢式】</strong>
public class Single {
private static Single single = new Single();
private Single()
{
}
public static Single getInstance(){
return single;
}
}
public class Demo { public static void main(String[] args) { Single s = Single.getInstance(); Single s1 = Single.getInstance(); System.out.println(s); System.out.println(s1); } }
兩個變數地址相同。
總結:單例類
1.私有構造方法;
2.本類中建立物件;
3.對外提供獲取本類對像的方法;
單例類在程式碼上的體現:
餓漢式:此類一載入就建立物件;上為餓漢式;
【懶漢式】
<span style="font-size:18px;">public class Single { private Single(){} <strong>1</strong>. </span><pre name="code" class="java"><span style="white-space:pre"><span style="font-size:18px;"> </span></span>
<span style="font-size:18px;"><span style="white-space:pre"> </span>private static Single single = <strong>null; 2</strong></span>
public static Single getInstance(){
3 if(single == null){single = new Single;} 4}}<span style="font-size:18px;"> <span style="white-space:pre"> </span> return single;</span>
開發時用餓漢式;
面試一般問懶漢式;多執行緒操作,物件不唯一;
餓漢式單例程鞏固
<span style="font-size:18px;">public class SuperMan {
private String name;
private SuperMan(String name) {
this.setName(name);
}
public static SuperMan superMan = new SuperMan("mj");
public static SuperMan getInstance() {
return superMan;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show() {
System.out.println(name + "flay");
}
}
public class Demo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SuperMan superMan = SuperMan.getInstance();
System.out.println(superMan);
superMan.show();
superMan.setName("mjj");
superMan.show();
}
}</span>