抽象工廠方法模式

一.概念編程

爲建立一組相關或者是相互依賴的對象提供一個接口,而不須要指定他們的具體實現類。app

二.優勢ide

分離接口與實現,客戶端使用抽象工廠來建立須要的對象,而客戶端根本就不知道具體的實現是誰,客戶端只是面向產品的接口編程而已,使其從具體的產品實現中解耦,同時基於接口與實現分離,使抽象該工廠方法模式在切換產品類時更加靈活、容易。對象

三. 缺點blog

 對類文件的爆炸性增長,不太容易擴展新的產品類接口

四.UML圖產品

五.實例class

/**
 * 計算器運算操做接口
 * Created by hm on 16/10/17.
 */

public abstract class OperatorInterface {

    /**
     * 運算操做數
     * @param num 可變參數
     */
   public abstract int operator(int ...num);
}
/**
 * 加法運算
 * Created by hm on 16/10/17.
 */

public class AddOperator extends OperatorInterface {
    @Override
    public int operator(int... num) {
        int sum = 0;
        if(num.length != 0){

            for (int a : num) {
                sum += a;
            }
        }
        return sum;
    }
}
/**
 * 工廠接口
 * Created by apple on 16/10/17.
 */

public interface ProductFactory {
    OperatorInterface createOperator();
}
/**
 * 加法工廠
 * Created by apple on 16/10/17.
 */

public class AddOperatorFactory implements ProductFactory {
    @Override
    public OperatorInterface createOperator() {
        return new AddOperator();
    }
}
相關文章
相關標籤/搜索