工厂方法模式

“每个类型的对象都有它们自己的工厂。”

构造类

还是用水果来举例,首先创建一个Fruit:

1
2
3
interface Fruit03 {
void color();
}

创建橘子类:

1
2
3
4
5
6
class Orange03 implements Fruit03 {
@Override
public void color() {
System.out.print("橘色");
}
}

创建苹果类:

1
2
3
4
5
6
class Apple03 implements Fruit03 {
@Override
public void color() {
System.out.print("苹果色");
}
}

构建工厂

工厂方法模式和简单工厂模式的不同之处就在于,工厂的创建,它会首先声明一个抽象工厂接口:

1
2
3
interface Fruit03Factory {
Fruit03 getFruit();
}

然后针对每个水果,分别实现它们自己的工厂,首先是苹果工厂:

1
2
3
4
5
6
class Apple03Factory implements Fruit03Factory {
@Override
public Fruit03 getFruit() {
return new Apple03();
}
}

然后是橘子工厂:

1
2
3
4
5
6
class Orange03Factory implements Fruit03Factory {
@Override
public Fruit03 getFruit() {
return new Orange03();
}
}

测试用例

1
2
3
4
5
public static void main(String[] args) {
Fruit03Factory aplfactory = new Apple03Factory();
Fruit03 fruit03 = aplfactory.getFruit();
fruit03.color();
}

设计模式的原则

遵守了开闭原则,不用去修改已存在的工厂,和简单工厂方法最大的区别就在于,它为每个类都配备了一个专属的工厂,这些工厂都实现了同一个抽象工厂接口。