通过不同类传递值的最佳设计模式

时间:2019-07-15 07:01:16

标签: java class design-patterns class-design system-design

我正在构建具有以下要求的可扩展系统:

  1. 每个请求将具有2个属性:类型,区域
  2. 根据类型和区域的值,将选择不同的配置
  3. 有超过20种以上的类需要根据type + region选择配置。
  4. 业务逻辑涉及在20多个类中调用30多个函数,因此无法传递区域和类型。业务逻辑根据产品类型和状态具有多个分支。主类包含业务逻辑,并调用不同类中的各个函数来完成业务逻辑。

实现此目的的一种方法是创建一个具有两个字段的类:type和region。在入口点,创建此类的对象,并将其传递给每个函数调用。根据传递的对象的type + region值,选择适当的配置。

除了在每个函数中传递type + region对象之外,还有什么优雅的解决方案吗?像动态扩展对象一样?或在入口点设置一个对象,然后通过扩展任何特定的类来重用它。我是系统设计和继承的新手,所以我想不出一个优雅的解决方案。

例如: 以下概述了业务逻辑。 MainLogic类中有20多个助手,并且每个助手都有5个以上的数据存储。我正在寻找一种优雅的解决方案,该解决方案不涉及在所有函数之间传递region + type。

@AllArgsConstructor
class MainLogic {
    BillingInfoHelper billingInfoHelper;
    ..........

    public Boolean executeRequest(RequestInput requestInput){
        final String region = requestInput.getRegion();
        final String type = requestInput.getType();

        final BillingInfo billingInfo = billingInfoHelper.get(region, type);
        ..............
    }
}

@AllArgsConstructor
class BillingInfoHelper {
    AccountIdDataStore accIdDataStore;
    BankNameDataStore bankNameDataStore;
    AddressDataStore addressDataStore;
    ........

    public BillingInfo get(String region, String type){
        String accountNumber = accIdDataStore.get(region, type);
        String bankName = bankNameDataStore.get(region, type);
        String address = addressDataStore.get(region, type);
        return new BillingInfo(accountNumber, bankName, address);
    }
}


@AllArgsConstructor
class AccountIdDataStore {
    Config configStore

    public String get(String region, String type) {
        configStore.getAccountNumber(region, type)
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使类型和区域这两个不同的变量在Java中成为静态变量。

class ClassName{
    public static String type = "some_value";
    public static String region = "some_value";
}

稍后,您可以使用ClassName.type

在其他任何类中使用这些变量