简介:

享元模式,属于结构型的设计模式。运用共享技术有效地支持大量细粒度的对象。

适用场景:

具有相同抽象但是细节不同的场景中。

优点:

把公共的部分分离为抽象,细节依赖于抽象,符合依赖倒转原则。

缺点:

增加复杂性。

代码:

//用户类
class User
{
    private $name;
    function __construct($name)
    {
        $this->name = $name;
    }
    public function getName()
    {
        return $this->name;
    }
}
//定义一个抽象的创建网站的抽象类
abstract class WebSite
{
    abstract public function use(User $user);
}
// 具体网站类
class ConcreteWebSite extends WebSite
{
    private $name = '';
    function __construct($name)
    {
        $this->name = $name;
    }
    public function use(User $user)
    {
        echo "{$user->getName()}使用我们开发的{$this->name}" . PHP_EOL;
    }
}
//网站工厂
class WebSiteFactory
{
    private $flyweights = [];
    public function getWebSiteGategory($key)
    {
        if (empty($this->flyweights[$key])) {
            $this->flyweights[$key] = new ConcreteWebSite($key);
        }
        return $this->flyweights[$key];
    }
}
$f = new WebSiteFactory();
$fx = $f->getWebSiteGategory('电商网站 ');
$fx->use(new User('客户A'));
$fy = $f->getWebSiteGategory('电商网站 ');
$fy->use(new User('客户B'));
$fl = $f->getWebSiteGategory('资讯网站 ');
$fl->use(new User('客户C'));
$fm = $f->getWebSiteGategory('资讯网站 ');
$fm->use(new User('客户D'));
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。