管理类
概念
可以模拟/代替管理员日常工作的系统
下面用停车场系统做演示
答题流程
- Clarify
- What:除题目中的名词外,从管理的名词考虑
- parking lot是什么类型的?如果楼有多层,停车位也是多层,则parking lot->parking level->parking space->upper/lower space
- parking lot 管理什么?vehicle/parking spot
- vehicle/parking spot有什么类型?公交车/摩托/轿车,残疾人车位/卡车车位…
- How:
- 如何停车?显示出每一层剩余车位的数量
- 免费还是付费?如何收费?根据时间收费
- What:除题目中的名词外,从管理的名词考虑
- Core object:有进有出,思考这个系统的input/output,并考虑其中的映射关系
- input:bus/car/motorcycle
- 不建议在parking lot中加
- List<Car> cars
的三个原因:不需要知道parkinglot中有什么车(不必要)、parkinglot会和car建立dependency,parkinglot不应该依赖于car而存在(不必须)、parkinglot是静态元素而车是动态元素,会不断修改其中的List(动态关系) - 使用一个单独的ticket类保存car和parking lot的关系
- 不建议在parking lot中加
- output:parking spot
- parking lot和parking spot是静态关系,parking lot依赖于parking spot,当parking spot发生变化时parking lot也要发生变化
- input:bus/car/motorcycle
- use Case:从停车场的角度进行思考
- Reservation: X
- Serve: park vehicle / get available count
- Check out: clear spot / calculate price
- Parking lot find the spot to clear
- update spot to be available
- update available count for each level
- Class:设计类图时可以使用ticket的形式保管信息
- 如何获取每一层的剩余空位数?反面:在ParkingLot类中定义
int floor1; int floor2;....
,违背了可扩展性。应当新建一个level类,在ParkingLot中使用List<Level> level;
- ParkingLot应当依赖于抽象类而不是具体类
- 如何获取每一层的剩余空位数?反面:在ParkingLot类中定义
- Correctness:
- validate use cases
- follow good practice(eg.停车场已停满)
- S.O.L.I.D
- Design pattern
- Singleton Design Pattern: ensure a class has only one instance, and provide a global point of acess to it.
// 1
public class ParkingLot{
private static ParkingLot _instance = null;
private List<Level> levels;
private ParkingLot(){
levels = new ArrayList<Level>();
}
public static synchronized ParkingLot getInstance(){
if(_instance == null){
_insatnce = new ParkingLot();
}
return _instance;
}
}
// 2
public class ParkingLot{
private ParkingLot(){}
private static class LazyParkingLot{
static final ParkingLot _instance = new ParkingLot();
}
public static ParkingLot getInstance(){
return LazyParkingLot._instance;
}
}
根据类图写代码
迪米特法则(law of demeter)
each unit should have only limited knowledge about other units: only unit “closely” related to the current unit. Each unit should only talk to its frients; don’t talk to strangers.
// bad
obj.getx().gety().getz().do();
//good
obj.doSomeThing();