简单工厂模式

咱们以水果为例介绍简单工厂模式

创建一个水果接口:

public interface Fruit {
    //对水果的描述
    void describe();
}

创建Apple类(具体产品类):

public class Apple implements Fruit{

    public void describe() {
        System.out.println("I am Apple");
    }

}

创建Orange类(具体产品类):

public class Orange implements Fruit{

    public void describe() {
        System.out.println("I am Orange");
    }

}

创建Banana类(具体产品类):

public class Banana implements Fruit{
    public void describe() {
        System.out.println("I am Banana");
    }
}

现在水果都准备好了,再来一家水果店SimpleFruitFactory(简单工厂类):

/**
 * @author chenyk
 * @date 2018年9月7日
 * 简单工厂类:水果厂
 */

public class SimpleFruitFactory {
    public static Fruit createFruit(String fruitType){
        switch (fruitType) {
        case "apple":
            return new Apple();
        case "orange":
            return new Orange();
        case "banana":
            return new Banana();
        default:
            return null;
        }
    }
}

好了,假如现在有顾客说要买橘子,怎么办呢?看下面代码:

public class ClientDemo {
    public static void main(String[] args) {
        Fruit fruit = SimpleFruitFactory.createFruit("orange");
        fruit.describe();
    }
}

这就是简单工厂模式,它的缺点是扩展性比较差,比如说,当新增一种水果时,需要新创建一个水果的具体产品类,同时要修改工厂类。

 

posted @ 2018-09-07 16:08  51life  阅读(166)  评论(0编辑  收藏  举报