0
Software Development

## Day44. 範例：文字積木 （蠅量模式）

情境：這是公司生產的文字積木

``````<?php

namespace App\Flyweight\Blocks;

class ConcreteBlock
{
/**
* @var string
*/
protected \$shape;

/**
* @var string
*/
public \$word;

/**
* @param string \$shape
* @param string \$word
*/
public function __construct(string \$shape, string \$word)
{
\$this->shape = \$shape;
\$this->word = \$word;
}

/**
* @return string
*/
public function getShape(): string
{
return \$this->shape;
}

/**
* @return string
*/
public function getWord(): string
{
return \$this->word;
}
}

``````
• 客戶端的使用方式
``````namespace App\Flyweight\Blocks;
<?php

namespace App\Flyweight\Blocks;

use App\Flyweight\Blocks\ConcreteBlock;

class Program
{
/**
* @return array
*/
public function getBlocks(): array
{
\$firstBlock = new ConcreteBlock('star', 'B');
\$secondBlock = new ConcreteBlock('square', 'E');
\$thirdBlock = new ConcreteBlock('square', 'A');
\$fourthBlock = new ConcreteBlock('square', 'R');

return [\$firstBlock, \$secondBlock, \$thirdBlock, \$fourthBlock];
}
}

``````

• 首先定義抽象的積木介面
``````<?php

namespace App\Flyweight\Blocks\Contracts;

interface Block
{
public function getShape();
public function display(string \$word): string;
}
``````

• 接著定義實體積木
``````<?php

namespace App\Flyweight\Blocks;

use App\Flyweight\Blocks\Contracts\Block;

class ConcreteBlock implements Block
{
/**
* @var string
*/
protected \$shape;

/**
* @param string \$shape
*/
public function __construct(string \$shape)
{
\$this->shape = \$shape;
}

/**
* @return string
*/
public function getShape(): string
{
return \$this->shape;
}

/**
* @param string \$word
* @return string
*/
public function display(string \$word): string
{
return \$word;
}
}
``````

``````<?php

namespace App\Flyweight\Blocks;

use App\Flyweight\Blocks\ConcreteBlock;
use App\Flyweight\Blocks\Contracts\Block;

class BlockFactory
{
/**
* @var Block[]
*/
protected \$blocks;

/**
* @param string \$shape
* @return ConcreteBlock
*/
public function getBlock(string \$shape): Block
{
if (!isset(\$this->blocks[\$shape])) {
\$this->blocks[\$shape] = new ConcreteBlock(\$shape);
}

return \$this->blocks[\$shape];
}
}
``````

• 最後修改客戶端的使用方式
``````<?php

namespace App\Flyweight\Blocks;

use App\Flyweight\Blocks\Block;

class Program
{
/**
* @return array
*/
public function getBlocks(): array
{
\$blockFactory = new BlockFactory();

\$firstBlock = \$blockFactory->getBlock('star');
// \$firstBlock->display('B');

\$secondBlock = \$blockFactory->getBlock('square');
// \$secondBlock->display('E');

\$thirdBlock = \$blockFactory->getBlock('square');
// \$thirdBlock->display('A');

\$fourthBlock = \$blockFactory->getBlock('square');
// \$fourthBlock->display('R');

return [\$firstBlock, \$secondBlock, \$thirdBlock, \$fourthBlock];
}
}

``````

[單一職責原則]

[開放封閉原則]

[裡氏替換原則]

（註：若不熟悉 UML 類別圖，可參考UML類別圖說明。）

ʕ •ᴥ•ʔ：原來共享經濟是用了蠅量模式的概念啊。