java eav模式_实体属性值模式(EAV 模式)

实体属性值(Entity--attribute--value EAV)模式,可以方便 PHP 实现 EAV 模型。

4.4.1. 目的

实体属性值模型(Entity-attribute-value EAV)是一种用数据模型描述实体的属性(属性,参数),可以用来形容他们潜在巨大,但实际上将适用于给定的实体的数量是相对较少。 在数学中,这种模式被称为一个稀疏矩阵 。 EAV也被称为对象的属性值的模式,垂直的数据库模型和开放式架构。

4.4.2. UML 图

1bc3c3d4fc5c21818bf7a323a5cdb014.png

4.4.3. 代码

您可以在 GitHub 查看这段代码。

Entity.php

namespace DesignPatterns\More\EAV;

class Entity

{

/**

* @var \SplObjectStorage

*/

private $values;

/**

* @var string

*/

private $name;

/**

* @param string $name

* @param Value[] $values

*/

public function __construct(string $name, $values)

{

$this->values = new \SplObjectStorage();

$this->name = $name;

foreach ($values as $value) {

$this->values->attach($value);

}

}

public function __toString(): string

{

$text = [$this->name];

foreach ($this->values as $value) {

$text[] = (string) $value;

}

return join(', ', $text);

}

}

Attribute.php

namespace DesignPatterns\More\EAV;

class Attribute

{

/**

* @var \SplObjectStorage

*/

private $values;

/**

* @var string

*/

private $name;

public function __construct(string $name)

{

$this->values = new \SplObjectStorage();

$this->name = $name;

}

public function addValue(Value $value)

{

$this->values->attach($value);

}

/**

* @return \SplObjectStorage

*/

public function getValues(): \SplObjectStorage

{

return $this->values;

}

public function __toString(): string

{

return $this->name;

}

}

Value.php

namespace DesignPatterns\More\EAV;

class Value

{

/**

* @var Attribute

*/

private $attribute;

/**

* @var string

*/

private $name;

public function __construct(Attribute $attribute, string $name)

{

$this->name = $name;

$this->attribute = $attribute;

$attribute->addValue($this);

}

public function __toString(): string

{

return sprintf('%s: %s', $this->attribute, $this->name);

}

}

4.4.4. 测试

Tests/EAVTest.php

namespace DesignPatterns\More\EAV\Tests;

use DesignPatterns\More\EAV\Attribute;

use DesignPatterns\More\EAV\Entity;

use DesignPatterns\More\EAV\Value;

use PHPUnit\Framework\TestCase;

class EAVTest extends TestCase

{

public function testCanAddAttributeToEntity()

{

$colorAttribute = new Attribute('color');

$colorSilver = new Value($colorAttribute, 'silver');

$colorBlack = new Value($colorAttribute, 'black');

$memoryAttribute = new Attribute('memory');

$memory8Gb = new Value($memoryAttribute, '8GB');

$entity = new Entity('MacBook Pro', [$colorSilver, $colorBlack, $memory8Gb]);

$this->assertEquals('MacBook Pro, color: silver, color: black, memory: 8GB', (string) $entity);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值