加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 两个构造函数,它们执行不同的操作但采用相同的数据类型

发布时间:2020-12-15 05:12:24 所属栏目:Java 来源:网络整理
导读:我最近遇到了我的MorseString类问题.我有两个不同的构造函数,它们执行不同的操作,但采用相同的数据类型: /* * Constructor that takes the Morse Code as a String as a parameter */public MorseString(String s) { if(!isValidMorse(s)) { throw new Ille
我最近遇到了我的MorseString类问题.我有两个不同的构造函数,它们执行不同的操作,但采用相同的数据类型:

/*
 * Constructor that takes the Morse Code as a String as a parameter
 */

public MorseString(String s) {
    if(!isValidMorse(s)) {
        throw new IllegalArgumentException("s is not a valid Morse Code");
    }
    // ...
}

/*
 * Constructor that takes the String as a parameter and converts it to Morse Code
 */

public MorseString(String s) {
    // ...
}

我想出了这个解决方案:

public MorseString(String s,ParameterType type) {
    if(type == ParameterType.CODE) {
        if(!isValidMorse(s)) {
            throw new IllegalArgumentException("s is not a valid Morse Code");
        }
        // Constructor that takes Morse
    } else {
        // Constructor that takes String
    }
}

但它看起来很难看.还有其他方法吗?

解决方法

由于其中一个构造函数正在期待现成的摩尔斯电码数据(因此它更像是“构造函数” – 从字面上构建数据中的对象),而另一个必须进行一些转换,因此制作一个更有意义静态工厂方法称为转换:

/*
 * Constructor that takes the Morse Code as a String as a parameter
 */

public MorseString(String s) {
    if(!isValidMorse(s)) {
        throw new IllegalArgumentException("s is not a valid Morse Code");
    }
    // ...
}

/*
 * Factory method that takes the String as a parameter and converts it to Morse Code
 */

public static MorseString convert(String s) {
    // ...
    return new MorseString(convertedString);
}

因此,如果您有一个有效的莫尔斯代码字符串,则使用构造函数将其转换为对象.但是,如果您有需要转换的数据,则可以调用静态工厂方法:

MorseString ms = MorseString.convert(myString);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读