浅谈Java设计模式——工厂方法模式(FactoryMethod)
一、概述
定义一个用于创建对象的接口,让子类决定实例化哪一个类。FactoryMethod使一个类的实例化延迟到其子类。
二、使用场景
1.当一个类不知道它所必须创建的对象的类的时候。
2.当一个类希望由它的子类来指定它所创建的对象的时候。
3.当类将创建对象的职责委托给多个帮助子类中的某一个,并且你希望将哪一个帮助子类是代理者这一信息局部化的时候。
三、类图
四、实现代码
Operation抽象类:
/**
* 运算超类
*/
public abstract class Operation {
public abstract double getResult(double t1, double t2);
}
OperationAdd类:
/**
* 加法操作
*/
public class OperationAdd extends Operation {
@Override
public double getResult(double t1, double t2) {
return t1 + t2;
}
}
OperationSubtraction类:
/**
* 减法操作
*/
public class OperationSubtraction extends Operation {
@Override
public double getResult(double t1, double t2) {
return t1 - t2;
}
}
Factory接口:
/**
* 工厂接口
*/
public interface Factory {
public Operation createOperation();
}
AddFactory类:
public class AddFactory implements Factory {
@Override
public Operation createOperation() {
return new OperationAdd();
}
}
SubtractionFactory类:
public class SubtractionFactory implements Factory {
@Override
public Operation createOperation() {
return new OperationSubtraction();
}
}
客户端代码:
public class Client {
public static void main(String[] args) {
Factory factory = new AddFactory();
Operation operation = factory.createOperation();
double result = operation.getResult(2, 2);
System.out.println("add operation result: " + result);
Factory factory1 = new SubtractionFactory();
Operation operation1 = factory1.createOperation();
double result1 = operation1.getResult(9, 3);
System.out.println("substractionFactory operation result: " + result1);
}
}