• S7:享元模式 Flyweight


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

    应用场景:

    A.减少对相同对象的重复创建

    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(2);
    
    $user3 = new User(3);
    
    echo($user1);
    echo($user2);
    echo($user3);
    

      

  • 相关阅读:
    Careercup
    Careercup
    Careercup
    Careercup
    Careercup
    Careercup
    Careercup
    Careercup
    Careercup
    Careercup
  • 原文地址:https://www.cnblogs.com/itfenqing/p/7788268.html
Copyright © 2020-2023  润新知