面向对象设计

面向对象设计速成。本文将以Parking Lot为例解释OO design

object对象

名词,每个名词都是一个对象。对于停车场系统来说,涉及到的名词有:

  • vehicle,包括truck, sedan, couple, etc.
1
2
3
class Vehicle {

}
  • slot, including regular slot, compact slot, handicapped slot(残障人士车位)
1
2
3
class Slot {

}
  • parking lot,整个停车场也是一个类
1
2
3
ParkingLot{

}

Inheritance/isa

继承是对象之间的关系,只要能用isa来描述的关系都能用继承来实现

  • truck is a vehicle, sedan is a vehicle, so they inherit from vehicle
1
2
3
4
// make parent class an abstract class
abstract class Vehicle {

}
1
2
3
class Truck extends Vehicle {

}
  • regular slot is a slot, compact slot, handicapped slot
1
2
3
4
// make parent class an abstract class
abstract class Slot {

}
1
2
3
class CompactSlot extends Slot {

}

Attribute/has

“类成员”,“属性”,“字段”,“特征” 都是一个东西,就是在类中定义的变量
能用“is+形容词/名词,或者是has+名词”描述的都可以写在成员里。“is+形容词”表示对象的属性,通常用基本数据类型表示;“has+名词”通常表示该对象拥有的“成员”,因为出现名词,(参照对象的定义)通常用另一个类或者类的数组表示。

  • For a vehicle, its size: big, regular or compact? its plate? What is its engine?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
abstract class Vehicle {
private int size; // 为什么用private?因为这些变量不能暴露给其他成员修改,但其他地方可能需要读取这些变量,于是我们需要写getter,就是用来读取私有变量的函数。
private String plate;
private EngineClass engine; // another class

// getter
int getSize() {
return size;
}
// 同样有getter对应的setter,setter最普遍的用处就是控制输入范围,比如初始化的时候想初始化一个巨大的车,输入一个很大的size,这时候用setter就能把关
void setSize(int size) {
if (size > SIZE_MAX) {
size = SIZE_MAX;
}
}
}
  • For a slot, what is it’s number? is occupied or not?
1
2
3
4
5
abstract class Slot {
private int slotNumber;
private boolean isOccupied;

}
  • For a parking lot, its size? How many slot it has? How many of those slot are occupied?
1
2
3
4
5
6
public class ParkingLot {
private List<Slot> regularSlots;
private List<Slot> compactSlots;
private List<Slot> handicappedSlots;
// use Map<car.plate, Slot> to denote all occupied slots
public Map<String, Slot> occupiedSlot;

Method/cando

方法就是写在类里面的函数,前面的getter和setter就属于类方法。一般自然语言中的“能做什么”都能写成类方法。

  • 停车这个函数
    Pause,先写到这,一会补上

Initialisation

初始化

Reference

Parking Lot

Black Jack