工厂方法模式
-
介绍
- 结构图:
- 结构图:
- 定义
定义一个用于创建对象的接口,让子类决定实例化哪个类。工厂方法使一个类的实例化延伸到其子类
- (自我总结)核心:
- 顶层工厂接口和一系列实现类
- 顶层产品接口和一系列实现类
-
优点:
- 解决了简单工厂需要维护的
if-else 列表
(极大程度上满足了开闭原则),选择使用移交给调用方 - 保留了简单工厂创建对象的隐蔽性
- 解决了简单工厂需要维护的
-
缺点:
- 需要维护大量的额外使用工厂类,并且需要由使用方决定如果选择(一定的)。
- 此模式相比较工厂方法类更加笨重
-
区别
- 简单工厂模式
- 从结构层次上,工厂方法模式将简单工厂的工厂类抽象并依赖Product的实例产生多个Product的工厂。也就是长生一个对像由原本的
Fectory --> realProduct
变成了IFectory --> realFectory --> realProduct
实现一个计算器
通过输入 + - ,对两个整型数字进行运算 。
一、结构图
通过图我们明白,我们可以看到工厂本身也被抽象化了。这样导致对调用者来说就需要在
使用层次
知道所有的Fectory的实现类
的使用。
但对于开发者来说,就不需要维护一个庞大的if-else的对象生成列表
,但是现在添加新的功能就不能只添加Operation还需要对应的Fectory
增加了开发的压力
二、代码
// 调用方 不属于工厂结构内部
public class FactoryMethodMain {
public static void main(String[] args) {
int num_a = 1;
int num_b = 1;
char char_oper = '+';
// 这里是由使用方选择使用对象的工厂
// 这里就需要使用方知道几乎所有的工厂类
OperationFectory operationFectory = new AddFectory();
// 生成对象不需要去考虑,所有工厂都用同一个接口方法
Operation operation = operationFectory.createOperation();
int return_c = operation.getResut(num_a, num_b);
System.out.println(return_c);
}
}
// Operation顶层工厂接口
public interface OperationFectory {
Operation createOperation();
}
// 加法工厂
public class AddFectory implements OperationFectory {
@Override
public Operation createOperation() {
return new AddOperation();
}
}
// 减法工厂
public class DescFectory implements OperationFectory {
@Override
public Operation createOperation() {
return new descOperation();
}
}
// Operation顶层抽象接口
public interface Operation {
// 计算抽象接口
int getResut(int num_a, int num_b);
}
// 加法计算器
public class AddOperation implements Operation {
@Override
public int getResut(int num_a, int num_b) {
return num_a + num_a;
}
}
// 减法计算器
public class descOperation implements Operation {
@Override
public int getResut(int num_a, int num_b) {
return num_a - num_b;
}
}