工厂方法模式(Factory Method Pattern)是一种创建型设计模式,它提供了一个接口用于创建对象,但允许子类决定实例化哪一个类。核心在于引入了一个工厂方法,这个方法由子类来实现,从而使得一个类的实例化延迟到其子类中进行。
**代码需求:**在设计模式-简单工厂:计算机案例中 添加两个计算方法类(指数,底数)。
工厂方法实现:
代码结构图
/**
* 运算类-基类
* @Author : MengYansong
* @create 2024/1/17 10:43
*/
public abstract class Operation {
/**
* 计算方法
*/
public abstract double getResult(double num1,double num2);
}
/**
* 加法实现类
*/
public class Addition extends Operation {
@Override
public double getResult(double num1, double num2) {
return num1 + num2;
}
}
/**
* 减法实现类
* @Author : MengYansong
* @create 2024/1/17 10:49
*/
public class Subtraction extends Operation {
@Override
public double getResult(double num1, double num2) {
return num1 - num2;
}
}
/**
* 基础工厂
*/
public class BaseFactory implements IFactory {
@Override
public Operation createOperation(String str) {
switch (str){
case "+":
return new Addition();
case "-":
return new Subtraction();
default:
return null;
}
}
}
/**
* 对数运算类
*/
public class LogCount extends Operation {
@Override
public double getResult(double num1, double num2) {
// 未对两个参数校验
return Math.log(num2) / Math.log(num1);
}
}
/**
* 计算指数运算类
*/
public class PowCount extends Operation {
@Override
public double getResult(double num1, double num2) {
// 未对参数进行校验
return Math.pow(num1,num2);
}
}
/**
* 高级工厂
*/
public class SeniorFactory implements IFactory {
@Override
public Operation createOperation(String str) {
switch (str){
case "pow":
return new PowCount();
case "log":
return new LogCount();
default:
return null;
}
}
}
/**
* 运算工厂类
*/
public interface IFactory {
Operation createOperation(String str);
}
/**
* 工厂类
*/
public class Factory {
public Operation createOperate(String str){
switch (str){
case "+":
case "-":
return new BaseFactory().createOperation(str);
case "pow":
case "log":
return new SeniorFactory().createOperation(str);
default:
return null;
}
}
}
/**
* 客户端
*/
public class FactoryDemo {
public static void main(String[] args) {
Factory factory = new Factory();
Operation operate = factory.createOperate("+");
System.out.println("加法" + operate.getResult(10, 10));
Operation operate2 = factory.createOperate("-");
System.out.println("减法" + operate2.getResult(10, 10));
Operation operate3 = factory.createOperate("pow");
System.out.println("指数" + operate3.getResult(10, 10));
Operation operate4 = factory.createOperate("pow");
System.out.println("对数" + operate4.getResult(15, 10));
}
}
运算结果:
Connected to the target VM, address: '127.0.0.1:55599', transport: 'socket'
加法20.0
减法0.0
指数1.0E10
对数5.76650390625E11
Disconnected from the target VM, address: '127.0.0.1:55599', transport: 'socket'
严格来说,是一种升级。当只有一个工厂时,就是简单工作模式,当有多个工厂时,就是工厂方法模式。类似由一维进化成了二维,更强大了