设计模式——工厂模式和策略模式的区别

工厂模式和策略模式的区别

在使用上,两者都有一个抽象类或接口,供不同的“产品”或者“策略”去继承或者实现,不同点在于,工厂模式中,具体产品的实例化发生在工厂内部,然后通过工厂的某个方法传递给外部使用,而策略模式是在外部实例化一个策略,然后传递到使用环境中,再由环境对其应用。这样说比较抽象,可以参考具体例子。

//工厂模式
//抽象产品
/** * 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);
    }
}

你可能感兴趣的:(设计模式,工厂模式,策略模式)