我的问题是,您可以在房间类的实例化时设置房间参数,但是如何设置房间类的聚合特征的属性,例如墙壁属性和 window 属性?因为我不想使用 setter ?还有别的办法吗?
因为我可以实例化房间,然后我必须单独添加墙壁和 window 的实例?因为我可以实例化 3 个房间,所以每个房间都有不同的 window 和墙壁尺寸?
ROOM CLASS < AGGREGATED WALL ARRAY LIST < AGREGGATED WINDOWS ARRAY LIST
谢谢
最佳答案
<罢工> 是的, builder 。喜欢罢工>
<罢工>public class Room {
private List<Window> windows = new ArrayList<Window>();
private List<Wall> walls = new ArrayList<Wall>();
private List<Door> doors = new ArrayList<Door>();
public Room(int windows, int walls, int doors){
for(int i=0; i < windows; i++)
windows.add(new Window());
//similarly for walls and Doors :)
}
//getters
}
罢工><罢工>罢工>
更新来自评论:OP希望避免setter,结果发现Windows可能是不同类型的。看来这是某种对作文能力的考验,has-a
东西。
我猜你需要这个。 弄清楚!
NOTE: I have written this in this editor, for conceptual understanding purpose, code may not compile
//you see rooms have walls, and many. So constructor takes List of
//windows and doors in each wall. So, a List of walls that has List
// (mixed bag) of windows and doors in each wall -- some may have no
//window/door, then 2nd list will be empty.
public class Room {
List<Wall> _walls = new ArrayList<Wall>();
public Room(List<List<Openable>> walls){
for(List<Openable> windowsOrDoors : walls){
this._walls.add(new Wall(windowsOrDoors));
}
}
}
//wall can have many doors and/or windows. We pass out mixed
// bag list here, constructor will figure out how to keep
//them in separate lists
public class Wall {
List<Door> doors = new ArrayList<Door>();
List<Window> windows = new ArrayList<Window>();
public Wall(List<Openable> openables){
for(Openable windowsOrDoor : openables){
if(windowsOrDoor instanceOf Window)
this.windows.add(windowsOrDoors);
else
this.doors.add(windowsOrDoors);
}
}
}
//Window class, simple class -- it is of type Openable
public class Window implements Openable{
public Window(int w, int h){
//do something
}
}
//Door class, simple class -- it is of type Openable
public class Door implements Openable{
public Door(int w, int h){
//do something
}
}
//Openable -- a common interface to Window and Door, you can use
//abstract class here and have getHeight, getWidth and other common
//methods. This just for the purpose that if you wanted to add another
//Window/Door class like `ArchedDoor` which has a `radius` as well,
//you will just write a `ArchedDoor implements Openable` and pass into
//the Room/Wall constructor. Nothing will break.
public interface Openable{}
关于java - 设置聚合特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9602089/