gpt4 book ai didi

java - 组合优于继承和紧耦合

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:41:24 24 4
gpt4 key购买 nike

我是一个完全的初学者,请原谅我的无知。我创建了一个项目,在其中我在某些类(class)中使用了合成。在我的 Cinema 类中,我有一个 Schedule 对象。

public class Cinema {        

private String name; //set via constructor
private int seatCount; // set in constructor
private int rowCount; // set in constructor
private int cleanUpTime; //set via constructor
private LocalTime openTime = LocalTime.of(9, 30);
private LocalTime closeTime = LocalTime.of(23, 59);
private LocalTime peakTime = LocalTime.of(16, 30);
private int costPerHour; //set via constructor
private Schedule schedule = new Schedule(this);

//Constructors, other methods....
}

时间表属于电影院。它的某些方法需要 Cinema 对象。没有电影院就没有时间表。

当阅读有关 OOP 的内容时,我被引导相信我创建了一个现在与另一个类紧密耦合的类,这可能很糟糕。

那么我该如何改进这个设计呢?

我似乎有几个紧密耦合的类。例如预订类和客户类。预订有一个客户,客户包含他们所做的所有预订的列表。

我以为我正在使用组合,那会很好,但现在我很困惑,因为我已经阅读了关于耦合的内容。

请帮助我理解。

最佳答案

必须有一些耦合。 Cinema 和 Schedule 并不是完全独立的。

A Schedule belongs to a Cinema.

到目前为止,还不错。

It needs a Cinema object for some of its methods.

没有。 Schedule 对象应该能够独立存在。

由于您没有提供任何代码,我将做出以下假设。

  • 电影院放映一部或多部电影。
  • 一部电影在一周中的每一天都有一个时间表,只要放映电影。

所以这是一个 Schedule 类。

public class Schedule {
private final Calendar showingTimestamp;

public Schedule(Calendar showingTimestamp) {
this.showingTimestamp = showingTimestamp;
}

public Calendar getShowingTimestamp() {
return showingTimestamp;
}

public int getShowingWeekday() {
return showingTimestamp.get(Calendar.DAY_OF_WEEK);
}

}

Schedule 类中唯一的字段包含放映日期和放映时间。我向您展示了如何使用 Calendar 方法获取工作日。

这是一个简单的 Movie 类。

public class Movie {
private final String name;

private List<Schedule> showingList;

public Movie(String name) {
this.name = name;
this.showingList = new ArrayList<>();
}

public void addShowing(Schedule schedule) {
this.showingList.add(schedule);
}

public List<Schedule> getShowingList() {
return Collections.unmodifiableList(showingList);
}

public String getName() {
return name;
}

}

Movie 类知道 Schedule 类。 Schedule 类不知道 Movie 类。

最后是 Cinema 类。

public class Cinema {

private final String name;

private List<Movie> currentMovieList;

public Cinema(String name) {
this.name = name;
this.currentMovieList = new ArrayList<>();
}

public void addCurrentMovie0(Movie movie) {
this.currentMovieList.add(movie);
}

public void removeMovie(Movie oldMovie) {
for (int index = currentMovieList.size() - 1; index >= 0; index--) {
Movie movie = currentMovieList.get(index);
if (movie.getName().equals(oldMovie.getName())) {
currentMovieList.remove(index);
}
}
}

public List<Movie> getCurrrentMovieList() {
return Collections.unmodifiableList(currentMovieList);
}

public String getName() {
return name;
}

}

Cinema 类了解 Movie 类,并间接了解 Schedule 类。 Movie 类不知道 Cinema 类。

希望对您有所帮助。

关于java - 组合优于继承和紧耦合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37142215/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com