构建器模式中的对象表示到底意味着什么?

what object representation in builder pattern exactly means?

我是设计新手 pattern.I 感觉我在理解构建器模式时遗漏了一些重要的部分。 对象表示在此定义中的确切含义是什么?

THE BUILDER PATTERN: Separates the construction of a complex object from its representation so that the same construction process can create different representations.

是指对象的内部结构(实例变量和成员函数)吗? 我在网上找过,但还是弄糊涂了,不胜感激!

根据GoF, the Builder pattern is a creational模式,因此,它解决了创建对象时的特定问题。

当您需要创建一个具有许多依赖项的复杂对象并且不可能或不切实际地同时获得所有这些依赖项时,就会出现对构建器模式的需求。

让我们以汽车装配线为例。并非所有的汽车都是平等的,尽管它们都有相似的结构(如车架、车轮、方向盘、刹车、灯),但它们可能在可选件上有所不同,如数字空调、太阳能屋顶、停车摄像头等.

这条装配线应该足够灵活,能够以最少的设置制造客户想要的任何配置的汽车。

假设 assembler 机器收到新车的蓝图,它必须 assemble 然后遵循该规格。

将其带入面向对象的软件工程世界,我们可能会:

interface ICar {
    public function getName();
    public function getColor();
    public function addComponent($component);
}

class CarImpl implements ICar {
    private $name, $color, $components = array();
    public function __construct($name, $color, array $components){
        $this->name = $name;
        $this->color = $color;
        $this->components = $components;
    }
    public function getName() { return $this->name; }
    public function getColor() { return $this->color; }
    public function addComponent($component) { $this->components[] = $component; }
}

class CarBuilder {
    private $buildClass = 'CarImpl';
    private $name, $color, $components = array();

    public function __construct($buildClass = null) {
        if ($buildClass !== null) {
            $this->buildClass = $buildClass;
        }
    }

    public function setName($name) {
        $this->name = $name;
    }

    public function setColor($color) {
        $this->color = $color;
    }

    public function addComponent($component) {
        $this->components[] = $component;
    }

    public function build() {
        return new ${this->buildClass}($this->name, $this->color, $this->components);
    }
}

// using...

$builder = new CarBuilder();
$builder->setName('Camaro');
$builder->setColor('Yellow');
$builder->addComponent('frame');
$builder->addComponent('bodywork');
$builder->addComponent('wheels');
$builder->addComponent('engine');
$builder->addComponent('black stripes');
$builder->addComponent('cybertronian core');

$myCar = $builder->build(); // yields Bumblebee!

所以,回答你的问题:

Is it means the object's internal struct(instance variable and member function)?

是的,指的是内部结构。通常,一个实例变量,因为在 PHP 中,通过向其添加方法来更改 class 合同不是一个好习惯。

虽然我上面的例子可能看起来很愚蠢,但为了简单起见,我故意这样做了。

但作为一项脑力练习,想一想如果某些组件有自己的依赖项,无法以正确的方式获取,会发生什么情况。然后您将能够延迟 CarImpl 对象,直到您可以满足其所有组件依赖项。

Design Patterns 的索引部分寻找参考资料似乎没有提供任何答案。

幸运的是,您的术语问题已得到解决 in this Wikibooks appendix,其中注明

  • The abstraction is only the visible part of your code outside. It is the contract between the provider and the client code. [...]

  • The representation is the way a problem is resolved. It follows the contract of what is given as input and what is expected to be returned. [...]

我想用更通俗的话说,抽象与接口相关,而表示与实际实现相关。

引号中的 [...] 是我的,表示我省略了不太重要的部分。