基于工厂模式的代码

2023.6.29

今天花费了时间去写了一个基于工厂模式的代码重构的demo,因为在不久之前的一次面试当中,面试官有问到代码重构相关的知识点,瞬间又多了一个知识薄弱点,那就简单总结一下对于代码重构方向的简单理解。

public int calculate(int a, int b, String operator) {
    int result = Integer.MIN_VALUE;
 
    if ("add".equals(operator)) {
        result = a + b;
    } else if ("multiply".equals(operator)) {
        result = a * b;
    } else if ("divide".equals(operator)) {
        result = a / b;
    } else if ("subtract".equals(operator)) {
        result = a - b;
    }
    return result;
}

上面的代码是重构前的代码,供大家参考一下,大家也可以自行发挥去重构这段代码,从表面来看的话,起什么没什么大问题,但是我们考虑问题一定要全面,没有做空值处理以及代码的结构存在冗余,不方便空能的拓展等。。

下面我们我们代码进行重构 , 常用的重构是基于工厂模式实现 , 核心思想是将功能封装成功能类,实现一个带有空值处理的操作工厂类:

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public interface Operation {   //定义工厂接口
    int apply(int a , int b);
}

/*
*定义操作类  add   ,  功能增加区
* */
class Addition implements Operation{
    @Override
    public int apply(int a , int b){
        return a+b;
    }
}

class Division implements Operation{
    @Override
    public int apply(int a , int b){
        return a-b;
    }
}

/*
* 实现操作工厂
* */
class OperationFactory{
    static Map<String, Operation> operationMap = new HashMap<String, Operation>();

    static {
        operationMap.put("add", new Addition());
        operationMap.put("divide" , new Division());
    }
    public static Optional<Operation> getOperation(String  Operator) {
        return Optional.ofNullable(operationMap.get(Operator));
    }
}

功能类引用:

class Calcuate {
    int culateUsingFactory(int a , int b , String operator){
        Operation targetOperation = OperationFactory
                .getOperation(operator)
                .orElseThrow(() -> new IllegalArgumentException("Invaild Operation"));  //自定义异常
        //orElseThrow()如果存在该值,返回包含的值,否则抛出由 Supplier 继承的异常
        return targetOperation.apply(a , b);
    }

    public static void main(String[] args) {
        Calcuate c = new Calcuate();
        System.out.println(c.culateUsingFactory(100 , 2 , "add"));
    }
}


在操作工厂类中用Optional获取操作对象,在实现类当中用orElseThrow判断获取对象是否起作用

大概总结一下,代码重构的核心思想就是将冗余或者重复不便于拓展的代码重新设计成为可读性高,便于拓展的代码。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
基于工厂模式的智能系统是一种软件设计模式,它通过使用工厂类来创建对象,而不是直接在代码中实例化对象。这种模式可以提供更好的灵活性和可扩展性,使系统更加智能化。下面是一个基于工厂模式的智能系统的示例: ```python # 定义一个抽象产品类 class IntelligentSystem: def __init__(self): self.name = "" def perform_operation(self): pass # 定义具体产品类 class KnowledgeManagement(IntelligentSystem): def __init__(self): self.name = "知识管理" def perform_operation(self): print("执行知识管理操作") class RemoteService(IntelligentSystem): def __init__(self): self.name = "远程服务" def perform_operation(self): print("执行远程服务操作") class SelfDiagnosis(IntelligentSystem): def __init__(self): self.name = "自我诊断" def perform_operation(self): print("执行自我诊断操作") class CollaborativeDiagnosis(IntelligentSystem): def __init__(self): self.name = "协同诊断" def perform_operation(self): print("执行协同诊断操作") # 定义一个工厂类 class IntelligentSystemFactory: def create_intelligent_system(self, system_type): if system_type == "knowledge_management": return KnowledgeManagement() elif system_type == "remote_service": return RemoteService() elif system_type == "self_diagnosis": return SelfDiagnosis() elif system_type == "collaborative_diagnosis": return CollaborativeDiagnosis() else: return None # 使用工厂类创建对象 factory = IntelligentSystemFactory() system1 = factory.create_intelligent_system("knowledge_management") system2 = factory.create_intelligent_system("remote_service") # 执行操作 system1.perform_operation() # 输出:执行知识管理操作 system2.perform_operation() # 输出:执行远程服务操作 ``` 这个示例中,我们定义了一个抽象产品类`IntelligentSystem`和四个具体产品类`KnowledgeManagement`、`RemoteService`、`SelfDiagnosis`和`CollaborativeDiagnosis`。工厂类`IntelligentSystemFactory`根据传入的参数来创建相应的产品对象。通过使用工厂类,我们可以根据需要创建不同类型的智能系统对象,并执行相应的操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

嘉文君

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值