1. 程式人生 > >單例、工廠、適配器、裝飾器

單例、工廠、適配器、裝飾器

print oid col instance 工廠 void public font run

單例

單例分為懶漢式和餓漢式

 1 public class Singleton {
 2     
 3     
 4     //餓漢加載
 5     //應用時才加載,節省內存
 6     private static Singleton instance;   
 7     private Singleton() {  
 8     }  
 9     public static Singleton getInstance(){  
10         if (instance == null) {  
11             synchronized
(Singleton.class) { 12 if (instance == null) { 13 instance = new Singleton(); 14 } 15 } 16 } 17 return instance; 18 } 19 20 21 //餓漢加載 22 //浪費內存 23 // private static Singleton singleton=new Singleton();
24 // public static Singleton getInstance(){ 25 // return singleton; 26 // } 27 28 public void run(){ 29 System.out.println("hellowolrd"); 30 } 31 }

工廠模式:

單例、工廠、適配器、裝飾器