设计模式之工厂模式

参考:http://www.runoob.com/design-pattern/factory-pattern.html

工厂模式代码示例

定义一个产品/对象的共有抽象,接口代码如下:

/**
 * @author Kevin
 * 
 * 饮料接口,提供 什么口味的方法
 */
public interface DrinkInterface {
    void taste();
}

实现以上接口的产品如下:

/**
 * @author Kevin
 * 可乐饮料
 */
public class ColeDrink implements DrinkInterface{

    @Override
    public void taste() {
        System.out.println("苦可乐");
    }

}
/**
 * @author Kevin
 * 雪碧饮料
 */
public class SpriteDrink implements DrinkInterface{

    @Override
    public void taste() {
        System.out.println("甜雪碧");
    }

}

工厂类如下:

/**
 * @author Kevin 2017-12-27
 * 饮料工厂
 *
 */
public class DrinkFactory {
    public static DrinkInterface getDrink(String taste){
        DrinkInterface drink = null;
        if(taste.equals("sprite")){
            drink = new SpriteDrink();
        }else if(taste.equals("cole")){
            drink = new ColeDrink();
        }
        return drink;
    }
}

最后写一个测试类:

/**
 * @author Kevin
 *  客户订单测试类
 */
public class CustomerOrderDemo {

    public static void main(String[] args) {
        DrinkInterface d = DrinkFactory.getDrink("sprite");
        d.taste();

        DrinkInterface d2 = DrinkFactory.getDrink("cole");
        d2.taste();
    }

}

工厂模式优缺点

虽然网上关于这个已经很多了,但是还是在这里再啰嗦一下。
优点就是简单且扩展容易,只需要实现接口,在工厂类中添加即可。
缺点是随着产品数量越来越多,实现类也会越来越多,是程序变得臃肿,类的数量不断增加,维护成本增加。

工厂模式应用与思考

在实际的开发中,到底我们什么时候用的上这样的模式呢?有的时候,我们不应该被模式模板化,其实很多时候我们都在使用这样的模式套路,只是不曾发现。是不是共同的东西我们抽象出了一个共有的接口,然后另外又提供了一个方便获取他们的类,这都该算是暗和了工厂模式的思路。比如在我的开发过程中,我们做对接接口开发,往往对方传过来的xml节点大同却小异,我们为了应对变化又方便大家svn开发,所以就提供一个接口,大家自己去实现解析节点,然后又通过一个工具类提供使用,这其实也算是工厂模式啦。

原文地址:https://www.cnblogs.com/Kevin-1992/p/12608404.html