gpt4 book ai didi

php - 这也违反得墨​​忒尔定律?或者扭曲它会是一种矫枉过正吗?

转载 作者:可可西里 更新时间:2023-10-31 23:15:19 24 4
gpt4 key购买 nike

很简单的一点:

class Point
{
private $x, $y;

public function __constructor($x, $y)
{
$this->x = $x;
$this->y = $y;
}

public function getX()
{
return $this->x;
}

public function getY()
{
return $this->y;
}
}

和一个圆圈

class Circle
{
private $r;
private $point;

public function __constructor (Point $point, $r)
{
$this->point = $point;
$this->r = $r;
}

public function getPoint() // here is the law breaking
{
return $this->point;
}
}

$circle = new Circle(new Point(1,2), 10);
$circle->getPoint()->getX(); // here is the law breaking
$circle->getPoint()->getY(); // here is the law breaking

当然它违反了得墨忒耳定律。所以让我折射它:

class Circle
{
private $r;
private $point;

public function __constructor (Point $point, $r)
{
$this->point = $point;
$this->r = $r;
}

public function getPointX()
{
return $this->point->getX();
}

public function getPointY()
{
return $this->point->getY();
}
}

$circle = new Circle(new Point(1,2), 10);
$circle->getPointX();
$circle->getPointY();

除了它看起来更好之外,我没有看到任何优势 - 只是两个额外的包装功能。从技术上讲,我再次拥有对 Point 的完全访问权限,并且无法将更多方法添加到 Point。第二种折射法还值得用吗?

最佳答案

除了这是一个基于意见的问题之外,我会这样做:

class Circle extends Point
{
private $r;

public function __constructor (Point $point, $r)
{
$this->x = $point->getPointX();
$this->y = $point->getPointY();
$this->r = $r;
}
}

$circle = new Circle(new Point(1,2), 10);
$circle->getPointX();
$circle->getPointY();

关于php - 这也违反得墨​​忒尔定律?或者扭曲它会是一种矫枉过正吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46622324/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com