代码中的OOP关联实施不违反封装

时间:2018-06-11 08:25:06

标签: php oop encapsulation ooad

这是驾驶员级和车级之间的关联情况 司机可以开车吗

  • 司机可以加速汽车
  • 司机可以检查他是否可以驾驶它
  • 司机可以检查他的驾驶执照是否可用

类图

enter image description here



我想在类图

中实现这个场景

示例代码在

之下

请不要这不是实际代码。这是虚拟代码

类驱动程序的代码

Class driver {

    private $car;
    private $license
    private $name


    public __construct(Car $car,$license){       
        $this->car      = $car;
        $this->$license = $license;
    }

    //driver can accelerate car
    public accelerating(){
       $this->car->accelerate();
    }

    checkDriverlicenceIsavailable(){
        $av = ($this->license)?true:false;
        return $av;
    }

    canDriveVehicle(){
        $cd = ($this->car->$vehicleType= 'luxuary car')?true:false
        return $cd;
    }

}

类Car的代码

Class Car {

    private $xlocation;
    private $ylocation;
    private $xspeed;
    private $yspeed;
    private $vehicleType;

    public __construct($xlocation,$ylocation,$xspeed = 0,$yspeed = 0,$vehicleType){
        $this->xlocation      = $xlocation;
        $this->ylocation      = $ylocation;
        $this->xspeed         = $xspeed;
        $this->yspeed         = $yspeed;  
        $this->vehicleType    = $vehicleType; 
    }

    public drive(){

        $this->xlocation + ($this->xspeed*(1));
        $this->ylocation + ($this->yspeed*(1));
    }


    public park(){
       $this->speed = 0;
    }


    public accelerate(){
       $this->xspeed++;
       $this->yspeed++;
    }
}
显示司机可以加速汽车,
在驱动程序类中有accelerating()方法,它将调用汽车类加速方法 在汽车类accelerate()方法中,仅适用于xspeedyspeed

这种方法是否正确?

这种方法不打破封装吗?

如果在驱动程序类中没有需要这样的方法来显示驱动程序可以加速汽车那么如何实现驱动程序可以在代码中加速汽车?

0 个答案:

没有答案