首页 > 其他 > 详细

S7:享元模式 Flyweight

时间:2017-11-05 19:46:50      阅读:274      评论:0      收藏:0      [点我收藏+]

运用共享技术有效的支持大量细粒度的对象.

UML:

技术分享

 

  

示例代码:
如果在工厂中,有用户,我们就直接调用,没有用户,我们就获取.减少对同一uid的user对象的重复创建.

interface FlyWeight
{
    public function __construct($uid);
}

class User implements FlyWeight
{
    protected $uid;
    public function __construct($uid)
    {
        $this->uid = $uid;
    }

    public function __toString()
    {
        return ‘uid‘ . $this->uid . PHP_EOL;
    }
}

class Factory
{
    public static $users = array();

    public static function getUser($uid)
    {
        if (! array_key_exists($uid, self::$users)) {
            self::$users[$uid] = new User($uid);
        }

        return self::$users[$uid];
    }
}

$user1 = Factory::getUser(1);
$user2 = Factory::getUser(1);

$user3 = new User(3);

echo($user1);
echo($user2);
echo($user3);

  

 

S7:享元模式 Flyweight

原文:http://www.cnblogs.com/itfenqing/p/7788268.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!