天天看點

java設計模式之單例模式和簡單工廠模式

深度探讨java設計模式

    • 一、單例模式
    • 二、簡單工廠模式

一、單例模式

1、單例類隻能有一個執行個體。
2、單例類必須自己建立自己的唯一執行個體。
3、單例類必須給所有其他對象提供這一執行個體。
           

代碼:

// An highlighted block
/**
 * 第一種:單例模式
 */
public class demo01 {
    private static demo01 d = null;
    private demo01(){}

    public static demo01 getExample(){
        int j = 1;
        if (d==null){
            System.out.println("第一次執行個體化");
            System.out.println("這個類隻能有一次執行個體化");
            d=new demo01();
        }else {
            j =j+1;
            System.out.println("這是第j次執行個體化");
            System.out.println("此次執行個體化将預設第一次");
        }
        return d;
    }
           

測試

public class Test {
    public static void main(String[] args) {
        demo01 d1 = demo01.getExample();
        demo01 d2 = demo01.getExample();
        System.out.println("判斷兩次執行個體是否一樣"+(d1 ==d2));
    }
}
//結果:第一次執行個體化
//這個類隻能有一次執行個體化
//這是第j次執行個體化
//此次執行個體化将預設第一次
//判斷兩次執行個體是否一樣true
           

二、簡單工廠模式

簡單工廠模式(Simple Factory Pattern)因為内部使用靜态方法根據不同參數構造不同産品對象執行個體,也稱靜态工廠方法模式。
在簡單工廠模式中,可以根據參數的不同傳回不同執行個體。簡單工廠模式專門定義一個類來負責建立其他類的執行個體,被建立的
執行個體通常都具有共同的父類。
           
/**
 * 操作工廠類
 * @author spring
 */
class OperationFactory {
    /**
     * 
     * @param operate 根據傳進來的操作符,選擇執行個體化響應的對象
     * @return
     */
    public static Operation createOperate(String operate){
        Operation oper = null;
        switch(operate){
            case "+":
                oper = new OperationAdd();
                break;
            case "-":
                oper = new OperationSub();
                break;
            case "*":
                oper = new OperationMul();
                break;
            case "/":
                oper = new OperationDiv();
                break;
        }
        return oper;
    }
}

/**
 * 操作抽象類,各種算數操作需要繼承此類,并實作getResult方法
 */
public abstract class Operation {
    abstract Integer getResult(int a, int b);
}

class OperationAdd extends Operation {
    @Override
    Integer getResult(int a, int b) {
        return a+b;
    }
}

class OperationSub extends Operation {
    @Override
    Integer getResult(int a, int b) {
        return a-b;
    }
}

class OperationMul extends Operation {
    @Override
    Integer getResult(int a, int b) {
        return a*b;
    }
}

class OperationDiv extends Operation {
    @Override
    Integer getResult(int a, int b) {
        return a/b;
    }
}

/**
 * 測試操作不再贅述
 */
public static void main(String[] args) {
        Operation oper = OperationFactory.createOperate("+");
        oper.getResult(10, 5);
}