zoukankan      html  css  js  c++  java
  • 享元模式 的另外一个例证

    <?php
    // 抽象享元角色
    abstract class Flyweight
    {
        abstract public function operation($state);
    }
    
    // 具体享元角色
    class ConcreteFlyweight extends Flyweight
    {
        private $_intrinsicState = null;
        public function __construct($state)
        {
            echo $state;
            $this->_intrinsicState = $state;
        }
        public function operation($state)
        {
            echo $state;
        }
    }
    
    // 不共享的具体享元,客户端直接调用
    class UnsharedConcreteFlyweight extends Flyweight
    {
        private $_intrinsicState = null;
        public function __construct($state)
        {
            echo $state;
            $this->_intrinsicState = $state;
        }
        public function operation($state)
        {
            echo $state;
        }
    }
    
    // 享元工厂角色
    class FlyweightFactory
    {
        private $_flyweights;
        public function __construct()
        {
            $this->_flyweights = array();
        }
        public function getFlyweigth($state)
        {
            if (isset($this->_flyweights[$state]))
            {
                return $this->_flyweights[$state];
            }
            else
            {
                return $this->_flyweights[$state] = new ConcreteFlyweight($state);
            }
        }
    }
    
    // client
    $flyweightFactory = new FlyweightFactory(); //新建一个享元工厂角色
    $flyweight = $flyweightFactory->getFlyweigth('state A');
    $flyweight->operation('other state A');
    
    $flyweight = $flyweightFactory->getFlyweigth('state B');
    $flyweight->operation('other state B');
    
    // 不共享的对象,单独调用
    $uflyweight = new UnsharedConcreteFlyweight('state A');
    $uflyweight->operation('other state A');
    ?>
  • 相关阅读:
    rCore-Tutorial-Book-v3学习笔记(五)
    rCore-Tutorial-Book-v3学习笔记(四)
    rCore-Tutorial-Book-v3学习笔记(三)
    rCore-Tutorial-Book-v3学习笔记(二)
    rCore-Tutorial-Book-v3学习笔记(一)
    OpenStack 命令行速查表(转载)
    mysql数据库总结笔记
    Owncloud迁移上云案例
    Python
    高等数学(微积分)
  • 原文地址:https://www.cnblogs.com/jiufen/p/5000495.html
Copyright © 2011-2022 走看看