1. 程式人生 > >每天學點設計模式之---單例模式

每天學點設計模式之---單例模式

這個模式是最簡單的,用它最主要是為了減少物件的建立,網上資料一大把,相信只要是開發,閉著眼睛都能寫出它來;
分兩種方式,惡漢式和飽漢式;

public class A {

    private A() {
    }

    //餓漢式
    private static final A ourInstance = new A();


    private static A inInstance;

    //飽漢式
    public static A getInstance() {
        if (inInstance == null) {
            synchronized
(A.class) { if (inInstance == null) { inInstance = new A(); } } } return inInstance; } }