設(shè)計(jì)模式(一)
單例設(shè)計(jì)模式
單例就是某個實(shí)體只產(chǎn)生一個對象,如果只能產(chǎn)生一個對象那么就需要將構(gòu)造函數(shù)設(shè)置為private的,那么就無法手動去創(chuàng)建該類的實(shí)體對象。
public class Student {
? ? ?private Student(){}
? ? ?private static Student s=new Student();
? ? ?public static Student getInstance(){
? ? ? ? ? return s;
? ? ?}
}
由于在類中直接創(chuàng)建除了實(shí)體的對象,這種方式被稱為餓漢式。但是如果創(chuàng)建該對象的時候需要消耗大量的資源,那么在不使用該對象的時候盡量不要去初始化
public class Student {
? ? ?private Student(){
? ? ?//消耗很多資源
? ? ?}
? ? ?private static Student s;
? ? ?public static Student getInstance(){
? ? ? ? ? if(s==null){
? ? ? ? ? ? ? ?s=new Student();
? ? ? ? ? }
? ? ? ? ? return s;
? ? ?}
}
上面這種方式避免了在不需要使用實(shí)體對象的時候?qū)?shí)體對象進(jìn)行初始化,但是在多線程并發(fā)的時候,會出現(xiàn)線程1執(zhí)行到s=new Student()的時候線程2執(zhí)行到if(s==null),這個時候就有可能創(chuàng)建兩個實(shí)體對象,為了避免以上的情況出現(xiàn)需要添加synchronized關(guān)鍵字。
public class Student {
? ? ?private static Student s;
? ? ?private Student(){}
? ? ?public static Student getInstance(){
? ? ? ? ? if(s == null){
? ? ? ? ? ? ? ?synchronized(Student.class){
? ? ? ? ? ? ? ? ? ? if(s == null){
? ? ? ? ? ? ? ? ? ? ? ? ?s = new Student();
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ?}
? ? ? ? ? }
? ? ? ? ? return instance;
? ? ?}
}