请举例说明工厂方法模式

时间:2015-06-24 04:17:49

标签: design-patterns factory

我阅读了factory模式和factory method模式之间的区别。

工厂方法模式将对象的实例化推迟到子类。它也是一种工厂方法,因为“Creator”的子项负责实现“Create”方法。

由于想要创建对象的类直接调用简单工厂。

但是对于工厂模式,我们也可以通过反射添加类注册并为要创建的对象使用一个子类层并将对象实例化逻辑保留在此子类中来解耦工厂类。

我没有得到符合上述工厂方法模式定义的工厂方法模式的示例。

您能为我提供工厂方法示例吗?

2 个答案:

答案 0 :(得分:2)

假设我们想要生产水果:

    public interface Fruit {
        public void plant();
        public void grow();
    }

    // concrete fruit Apple
    public class Apple implements Fruit {
        @Override
        public void plant() {
            System.out.println("Apple is planted.");
        }
        @Override
        public void grow() {
            System.out.println("Apple is growing.");
        }
    }

    // concrete fruit Banana
    public class Banana implements Fruit {
        @Override
        public void plant() { ... }
        @Override
        public void grow() { ... }
    }

factory 模式中,有一个工厂类负责生成新实例。 虽然缺点是如果添加了一种类型的实例,则必须更改工厂类的逻辑

示例:

// Factory class
public class FruitGarden {
    public static Fruit createFruit(String fruitName) throws Exception {
        if(fruitName.equals("Apple")) {
            return new Apple();
        } else if(fruitName.equals("Banana")) {
            return new Banana();
        } else {
            System.out.printf("Sorry! %s not supported.\n", fruitName);
            throw new Exception();
        }
    }
    /* another way to create instance
    public static Fruit createApple() {
        return new Apple();
    }
    public static Fruit createBanana() {
        return new Banana();
    }
    */
}

工厂方法 模式中,有一个抽象工厂代表新实例的创建。不同类型的实例由不同的具体工厂创建。所有这些具体工厂都实现了抽象工厂接口或扩展抽象工厂类。 如果添加了一个新类型,只需添加一个具体工厂,因此它具有更强的可扩展性

示例:

// abstract factory interface
public interface FruitGarden {
    public Fruit createFruit();
}

// concrete factory which is responsible producing Apple
public class AppleGarden implements FruitGarden {
    @Override
    public Fruit createFruit() {
        return new Apple();
    }
}

// concrete factory which is responsible producing Banana
public class BananaGarden implements FruitGarden {
    @Override
    public Fruit createFruit() {
        return new Banana();
    }
}

答案 1 :(得分:0)

Java Collection.iterator()是一种工厂方法。

集合的具体实现决定了此方法返回的具体迭代器。