编码风格和组织

Coding style and organization

所以我目前正在为一个暑期项目制作一个飞机预订系统,以保持与 Java 的新鲜感。对于任何预订系统,它都需要大量 classes 和方法。目前我正在导入舰队。

我的主要方法是充当我的程序的时间顺序指南。

public static void main(String[] args){
    //start here 
    //accept passenger credentials 
    //place passenger in seat on plane
}

我的问题是格式问题。当我想为我的机队启动 "making" 我的飞机时。它有点像这样。

//...
Airplane Boeing737 = new Airplane(seats[], nameOfAircraft);

这将放置我构建飞机所需的所有值,显然飞机构造函数有更多变量。

我的想法是在 Airplane class 中创建一个方法来为我做这件事。但为了做到这一点,我需要为另一个 class (使用我的主要方法的那个)调用一个空白构造函数来查看它。出于某种原因,我觉得这是一种可怕的形式。有一个更好的方法吗?

我发布的另一个想法是修改构造函数,使其不接受任何参数,并让其执行所有操作。我觉得那是我应该做的,但我不能 100% 确定那是正确的选择。我想我的总体问题是在这种情况下最佳做法是什么。

暂时忘记主要方法,您不知道它是命令行程序、带有 UI 的桌面应用程序、Web 服务还是什么。您不知道它是独立的还是托管在某些框架或应用程序服务器中。

我建议从单元测试开始,并使用 TDD 驱动域模型/业务逻辑的设计。

您不想看到像 Boeing737 这样的硬编码。它将从其他来源获取输入,例如输入,xml 文件,现有数据库,其他系统。

然后您将动态创建 Airplane 的实例。您将从 UI 或 DB 或 XML 解析器向构造函数传递类似 DTO 的内容。还有其他方法,例如查找工厂模式,但恕我直言,它们往往被过度使用。

您的开始方式似乎与现实世界中任何人所做的都不相符。很难给出更好的建议。

使用构建器模式,这将允许您:

  • 构建事件的动态方式
  • 可维护代码(您可以在需要时添加更多参数)
  • 在创建时保持对象的完整性

Joshua Bloch 在 Effective Java 第 1 章第 2 条中指出:

Luckily, there is a third alternative that combines the safety of the telescoping constructor pattern with the readability of the JavaBeans pattern. It is a form of the Builder pattern. Instead of making the desired object directly, the client calls a constructor (or static factory) with all of the required parameters and gets a builder object.

修改他的例子:

//Builder Pattern
public class Airplane  {
    private final int[] seats;
    private final String name;
    private final int maxSpeed;
    private final int maxPassengers;

    public static class Builder {
        // Required parameters
        private final int[] seats;
        private final String name;

        // Optional parameters - initialized to default values
        private int maxSpeed = 1000;
        private int maxPassengers = 150;

        public Builder(int[] seats, String name) {
            this.seats = seats;
            this.name = name;
        }

        public Builder maxSpeed(int val) {
            maxSpeed = val;
            return this;
        }

        public Builder maxPassengers(int val) {
            maxPassengers = val;
            return this;
        }

        public Airplane build() {
            return new Airplane(this);
        }
    }

    private Airplane(Builder builder) {
        seats = builder.seats;
        name = builder.name;
        maxSpeed = builder.maxSpeed;
        maxPassengers = builder.maxPassengers;
    }
}

然后你就可以创造几架不同的飞机

public static void main(String[] args) {
    // only mandatory params
    Airplane boeing747  = new Airplane.Builder(new int[] {1,0,1}, "boeing747").build();
    // just one param
    Airplane boeing646  = new Airplane.Builder(new int[] {1,1,1}, "boeing646").maxPassengers(250).build();
    // all params
    Airplane fighter    = new Airplane.Builder(new int[] {1,0,0}, "fighter_1").maxPassengers(3).maxSpeed(1600).build();
}