設計模式(一)
單例設計模式
單例就是某個實體只產生一個對象,如果只能產生一個對象那么就需要將構造函數設置為private的,那么就無法手動去創建該類的實體對象。
public class Student {
? ? ?private Student(){}
? ? ?private static Student s=new Student();
? ? ?public static Student getInstance(){
? ? ? ? ? return s;
? ? ?}
}
由于在類中直接創建除了實體的對象,這種方式被稱為餓漢式。但是如果創建該對象的時候需要消耗大量的資源,那么在不使用該對象的時候盡量不要去初始化
public class Student {
? ? ?private Student(){
? ? ?//消耗很多資源
? ? ?}
? ? ?private static Student s;
? ? ?public static Student getInstance(){
? ? ? ? ? if(s==null){
? ? ? ? ? ? ? ?s=new Student();
? ? ? ? ? }
? ? ? ? ? return s;
? ? ?}
}
上面這種方式避免了在不需要使用實體對象的時候對實體對象進行初始化,但是在多線程并發的時候,會出現線程1執行到s=new Student()的時候線程2執行到if(s==null),這個時候就有可能創建兩個實體對象,為了避免以上的情況出現需要添加synchronized關鍵字。
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;
? ? ?}
}