所有三种Factory类型都做同样的事情:它们是一个“智能构造函数”。
假设您希望能够创建两种水果:Apple和Orange。
工厂
Factory is "fixed", in that you have just one implementation with no subclassing. In this case, you will have a class like this:
class FruitFactory {
public Apple makeApple() {
// Code for creating an Apple here.
}
public Orange makeOrange() {
// Code for creating an orange here.
}
}
用例:在构造函数中构造Apple或Orange都太复杂了。
工厂方法
Factory method is generally used when you have some generic processing in a class, but want to vary which kind of fruit you actually use. So:
abstract class FruitPicker {
protected abstract Fruit makeFruit();
public void pickFruit() {
private final Fruit f = makeFruit(); // The fruit we will work on..
<bla bla bla>
}
}
...然后你可以通过在子类中实现一个工厂方法来重用fruitpick . pickfruit()中的通用功能:
class OrangePicker extends FruitPicker {
@Override
protected Fruit makeFruit() {
return new Orange();
}
}
抽象工厂
Abstract factory is normally used for things like dependency injection/strategy, when you want to be able to create a whole family of objects that need to be of "the same kind", and have some common base classes. Here's a vaguely fruit-related example. The use case here is that we want to make sure that we don't accidentally use an OrangePicker on an Apple. As long as we get our Fruit and Picker from the same factory, they will match.
interface PlantFactory {
Plant makePlant();
Picker makePicker();
}
public class AppleFactory implements PlantFactory {
Plant makePlant() {
return new Apple();
}
Picker makePicker() {
return new ApplePicker();
}
}
public class OrangeFactory implements PlantFactory {
Plant makePlant() {
return new Orange();
}
Picker makePicker() {
return new OrangePicker();
}
}