我的问题是,您可以在房间类的实例化中设置房间参数,但是如何设置房间类的聚合特征的属性,例如墙属性和窗口属性?因为我宁愿不使用setter?还有另一种方式吗?
因为我可以实例化房间,然后我必须添加墙壁和窗户的实例?由于我可以实例化3个房间,每个房间有不同的窗户和墙壁尺寸?
ROOM CLASS < AGGREGATED WALL ARRAY LIST < AGREGGATED WINDOWS ARRAY LIST
由于
答案 0 :(得分:3)
<击> 是的,构造函数。 LIke
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
。
我想你需要这个。 弄清楚!
注意:我已在此编辑器中编写此内容,出于概念上的理解目的,代码可能无法编译
//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{}
答案 1 :(得分:0)
我不确定我理解你,
但您可以将参数添加到房间的构造函数中,然后使用这些参数作为其构造函数的参数来启动房间的墙(您也可以向其构造函数添加参数)
你的构造函数看起来像这样:
public Room(WinSize[] windowsSizes, Color[] wallsColors){
for(int i = 0 ; i < WinSize.length ; i++)
{
windows.add(new Window(windowsSizes[i]));
}
}
(假设你有一些像WinSize等的课程。)
答案 2 :(得分:0)
这个问题缺少一些上下文,但总的来说,我可以说是的,你不会为聚合的计算字段创建公共setter。
通常你有私有方法来更新计算字段,这些方法是从构造函数和/或公共字段的setter调用的(也就是说,每次修改公共字段时都会更新计算字段)。 / p>