You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于JSON中Country值生成Phone前缀的实现方案咨询

解决方案

一、使用Builder模式+Switch语句实现

完全可以通过Builder模式结合switch语句实现需求,核心是在Builder类中新增一个根据国家值设置电话前缀的方法。

示例代码如下:

public class Phone {
    private String phonePrefix;

    // 私有构造方法,仅由Builder调用
    private Phone(Builder builder) {
        this.phonePrefix = builder.phonePrefix;
    }

    public static class Builder {
        private String phonePrefix;

        // 根据国家设置前缀的方法
        public Builder withCountry(String country) {
            switch (country) {
                case "United Kingdom":
                    this.phonePrefix = "+44";
                    break;
                case "United States":
                    this.phonePrefix = "+1";
                    break;
                case "China":
                    this.phonePrefix = "+86";
                    break;
                // 可扩展更多国家的映射
                default:
                    this.phonePrefix = ""; // 或抛出非法参数异常
            }
            return this;
        }

        // 构建Phone实例
        public Phone build() {
            return new Phone(this);
        }
    }
}

使用时只需传入国家参数即可自动生成对应前缀的Phone对象:

// 假设basicData是已获取的BasicData对象
Phone phone = new Phone.Builder()
        .withCountry(basicData.getCountry())
        .build();

二、结合Lombok注解实现

Lombok的@Builder注解本身不直接支持动态赋值逻辑,但可以通过扩展自动生成的Builder类,添加自定义方法来实现需求,既享受Lombok简化代码的便利,又能实现业务逻辑。

示例代码:

import lombok.Builder;
import lombok.Getter;
import java.util.Map;

@Getter
@Builder
public class Phone {
    private String phonePrefix;

    // 扩展Lombok自动生成的PhoneBuilder类
    public static class PhoneBuilder {
        // 抽离映射关系为静态常量,更易维护
        private static final Map<String, String> COUNTRY_PREFIX_MAP = Map.of(
                "United Kingdom", "+44",
                "United States", "+1",
                "China", "+86"
        );

        public PhoneBuilder withCountry(String country) {
            this.phonePrefix = COUNTRY_PREFIX_MAP.getOrDefault(country, "");
            return this;
        }
    }
}

使用方式简洁直观:

Phone phone = Phone.builder()
        .withCountry(basicData.getCountry())
        .build();

优化建议

如果国家与前缀的映射较多,优先使用静态Map维护映射关系,相比switch语句更易于扩展和维护,新增国家只需在Map中添加键值对即可,无需修改分支逻辑。

内容的提问来源于stack exchange,提问作者jamesp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 04:55:17