設計模式——工廠模式和策略模式的區別

工廠模式和策略模式的區別

在使用上,兩者都有一個抽象類或接口,供不同的“產品”或者“策略”去繼承或者實現,不同點在於,工廠模式中,具體產品的實例化發生在工廠內部,然後通過工廠的某個方法傳遞給外部使用,而策略模式是在外部實例化一個策略,然後傳遞到使用環境中,再由環境對其應用。這樣說比較抽象,可以參考具體例子。

//工廠模式
//抽象產品
/**
 * Created by zhangx-ae on 2016/4/13.
 */
public interface IProduct {
    void action();
}
//產品A
public class ProductA implements IProduct {
    @Override
    public void action() {
        System.out.println("我是產品A");
    }
}
//產品B
public class ProductB implements IProduct {
    @Override
    public void action() {
        System.out.println("我是產品B");
    }
}
//產品C
public class ProductC implements IProduct {
    @Override
    public void action() {
        System.out.println("我是產品C");
    }
}
//簡單工廠
/**
 * Created by zhangx-ae on 2016/4/13.
 * 簡單工廠中只能通過接受創建產品的參數確定創建相應的對象,
 * 當有新的產品的時候還需要修改工廠代碼,很明顯不符合開閉原則,
 * 這裏只是比較工廠模式和策略模式的區別,因此只採用簡單工廠模式進行說明
 */
public class Factory {
    public IProduct getProduct(String productType){
        if(productType.equals("A")){
            return new ProductA();
        }else if(productType.equals("B")){
            return new ProductB();
        }else if(productType.equals("C")){
            return new ProductC();
        }
        return null;
    }
}
//客戶端
/**
 * Created by zhangx-ae on 2016/4/13.
 */
public class ClientDemo {
    public static void main(String[] args) {
        Factory factory = new Factory();
        IProduct product = factory.getProduct("A");
        product.action();
    }
}

//策略模式
/**
 * Created by zhangx-ae on 2016/4/13.
 * 計算存款利息
 */
public interface IStrategy {
    double calcInterests(double investment);
}
/**
 * Created by zhangx-ae on 2016/4/13.
 * 定期存款一年
 */
public class StrategyA implements IStrategy {
    @Override
    public double calcInterests(double investment) {
        System.out.println("計算定期利息");
        return investment * 0.015;
    }
}
/**
 * Created by zhangx-ae on 2016/4/13.
 * 活期利息
 * 爲了突出重點,這裏簡化了計算方法
 */
public class StrategyB implements IStrategy {
    @Override
    public double calcInterests(double investment) {
        System.out.println("計算活期利息");
        return investment * 0.008;
    }
}
//應用環境
public class GetInterests {
    private IStrategy strategy;
    /**
     * 傳入一個具體的計算利息的策略對象
     * @param strategy 具體的策略對象
     */
    public GetInterests(IStrategy strategy){
        this.strategy = strategy;
    }
    /**
     * 根據具體策略計算利息
     * @param investment  本金
     * @return             利息
     */
    public double getInterests(double investment){
        return this.strategy.calcInterests(investment);
    }
}
//客戶端
/**
 * Created by zhangx-ae on 2016/4/13.
 */
public class ClientDemo {
    public static void main(String[] args) {
        IStrategy strategy = new StrategyA();
        GetInterests getInterests = new GetInterests(strategy);
        double interests = getInterests.getInterests(1000);
        System.out.printf("利息是:" + interests);
    }
}
發佈了30 篇原創文章 · 獲贊 3 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章