在另一个类中示例化类数组- Dart语言

rjee0c15  于 2022-12-15  发布在  其他
关注(0)|答案(2)|浏览(82)

我创建了一个包含墙的高度和宽度的Wall类,我需要在Room类中创建一个包含四个Wall类的列表,我该怎么做呢?我不想使用List,还有别的方法吗?对不起,我是OOP编程的新手。

void main() {
  
  Wall wall = Wall();
  
  print(wall.totalArea);
  wall.height = 4;
  wall.width = 4;
  wall.getAreaTotal();
  print(wall.totalArea);
}

class Room {
 
}

class Wall {
  double height;
  double width;
  late double totalArea;
  
  Wall({
     this.height = 1,
     this.width = 1,
  }) {
    getAreaTotal();
  }
  
  void getAreaTotal(){
    totalArea = height * width;
  }
}
htrmnn0y

htrmnn0y1#

这个房间有四面墙。如果我们假设一个长方形的房间,事情可能会变得更复杂。
最常用的方法是不假设四面墙,而只假设房间有一系列墙。

class Wall {
  final double height;
  final double width;
  Wall({required this.height, required this.width});
  double get totalArea => height * width;
}
class Room {
  final List<Wall> walls;
  Room(Iterable<Wall> walls) : walls = List.unmodifable(walls);
}

void main() {
  var room = Room([
    Wall(width: 4, height: 4),
    Wall(width: 2, height: 4),
    Wall(width: 4, height: 4),
    Wall(width: 2, height: 4),
  ]);
  var wallArea = 0.0;
  for (var wall in room.walls) wallArea += totalArea;
}

这允许任何墙壁组合,为您的基本L形房间与六面墙,或七边形房间的风格。
在某些情况下,你可以通过假设来使事情变得更容易。就像一个长方形的房间总是有相同的相对的墙壁,并且到处都有相同的高度。
然后您可以:

class RectangularRoom implements Room {
  final double length1;
  final double length2;
  final double height;
  final List<Room> rooms;
  RectangularRoom({
      required this.length1, 
      required this.length2, 
      required this.height}) 
      : rooms = _createWalls(length1, length2, height);
  static List<Room> _createWalls(
      double length1, double length2, double height) {
    var wall1 = Wall(length: length1, height: height);
    var wall2 = Wall(length: length2, height: height);
    return List.unmodifiable([wall1, wall2, wall1, wall2]);
  }
}

或者,您可以假设房间以某种方式定向:

// Also assumed rectangular.
class OrientedRoom extends Room {
  final Wall northWall;
  final Wall westWall;
  final Wall southWall => northWall;
  final Wall eastWall => westWall;
  OrientedRoom({
      required double length1, 
      required double length2, 
      required double height
  }) : this._(Wall(length: length1, height: height), 
              Wall(length: length2, height: height));

  OrientedRoom._(this.northWall, this.westWall) 
      : super([northWall, westWall, northWall, westWall]);
}

这允许您命名各个墙,并为每个墙提供一个class字段。
这么多的选择,哪一个适合你取决于你的用例,你将使用对象做什么。

5fjcxozz

5fjcxozz2#

就像@Dimon在评论中说的,你可以通过为你想要在房间里的每一面墙添加一个属性来管理它。
大概是这样的

class Room {
  final Wall leftWall;
  final Wall rightWall;
  final Wall topWall;
  final Wall bottomWall;

  Room(this.leftWall, this.rightWall, this.topWall, this.bottomWall);

}

并按如下方式创建您的文件室:

var room = Room(Wall(height: 15, width: 20), Wall(height: 15, width: 8),
        Wall(height: 15, width: 3), Wall(height: 15, width: 22));

相关问题