【问题标题】:How to separate a common code from implementation specific code?如何将通用代码与实现特定代码分开?
【发布时间】:2022-01-06 03:02:45
【问题描述】:

我有这样的事情:

switch(type){
    case "CAR":
       return new Car();
    case "BIKE":
       return new Bike();
}

现在,需要为两者添加一个通用 API,以检查输入类型是否有效,仅当 validateFlag 为 true 时。

你能在这里推荐一些设计吗?什么是最好的搭配?

我在想这样的事情:

if(flag== true)
  return new Validator();
switch(type){
    case "CAR":
       return new Car();
    case "BIKE":
       return new Bike();
}```

【问题讨论】:

  • 方法的返回类型是什么? @Turtle 认为它是 CarBike 的常见超类,这是有道理的,但如果您还可以返回 CarBike,则返回 Validator 没有多大意义。
  • 如果它不是一种汽车或自行车,你认为我们应该如何分离它,我们可以在调用它本身时添加一个 if else 块,但想法是避免 if else 的,而是使用一些设计模式
  • 我不明白你的问题

标签: java oop conditional-statements factory


【解决方案1】:

您可能想在此处使用inheritance。看看下面的示例代码。

class Vehicle {
    protected boolean mIsValid;
    
    public Vehicle() {}
    
    public boolean isValid() {
        return mIsValid;
    }
}

class Car extends Vehicle {
    public Car() {
        super();
        mIsValid = true;
    }
}

class Bike extends Vehicle {
    public Bike() {
        super();
        mIsValid = false;
    }
}

【讨论】:

    猜你喜欢
    • 2018-03-31
    • 2019-12-26
    • 2019-04-25
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多