面向对象设计
面向对象设计速成。本文将以Parking Lot为例解释OO design
object对象
名词,每个名词都是一个对象。对于停车场系统来说,涉及到的名词有:
- vehicle,包括truck, sedan, couple, etc.
1 | class Vehicle { |
- slot, including regular slot, compact slot, handicapped slot(残障人士车位)
1 | class Slot { |
- parking lot,整个停车场也是一个类
1 | ParkingLot{ |
Inheritance/isa
继承是对象之间的关系,只要能用isa来描述的关系都能用继承来实现
- truck is a vehicle, sedan is a vehicle, so they inherit from vehicle
1 | // make parent class an abstract class |
1 | class Truck extends Vehicle { |
- regular slot is a slot, compact slot, handicapped slot
1 | // make parent class an abstract class |
1 | 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 | abstract class Vehicle { |
- For a slot, what is it’s number? is occupied or not?
1 | abstract class Slot { |
- For a parking lot, its size? How many slot it has? How many of those slot are occupied?
1 | public class ParkingLot { |
Method/cando
方法就是写在类里面的函数,前面的getter和setter就属于类方法。一般自然语言中的“能做什么”都能写成类方法。
- 停车这个函数
Pause,先写到这,一会补上
Initialisation
初始化