2023年12月28日 星期四

favoring composition over inheritance and dependency injection

// demo of favoring composition over inheritance and construction with dependency injection


class Movement {

public void move();

};

class Wheel: Movement {};

class Turbine: Movement {};


class Control {

public void control();

};

class Handle: Control {};

class Dashboard: Control {};

class Handlebar: Control {};


class Vehicle {

Movement movement;

Control controll;

Vehicle(Movement m, Control c) {

this.movement = m;

this.control = c;

}

};

class Car: Vehicle {};

class MotorBike: Vehicle {};

class Jet: Vehicle {};


int main () {

Vehicle vehicles[] = {

new Jet (new Turbine(), new Dashboard()), 

new Car (new Wheel(), new Handle()), 

new MotorBike(new Wheel(), new Handlebar())

};


for (v: vehicles) {

v->move();

}


return 0

}