美文网首页
组合实体模式

组合实体模式

作者: 散装咖啡 | 来源:发表于2017-05-30 02:47 被阅读14次
    //compositeEntity
    class DependentObject1
    {
        private $data = null;
        
        public function setData($data)
        {
            $this->data = $data;
        }
        
        public function getData()
        {
            return $this->data;
        }
    }
    
    class DependentObject2
    {
        private $data = null;
        
        public function setData($data)
        {
            $this->data = $data;
        }
        
        public function getData()
        {
            return $this->data;
        }
    }
    
    class CoarseGrainedObject
    {
        public $data1 = null;
        public $data2 = null;
        
        public function __construct()
        {
            $this->data1 = new DependentObject1();
            $this->data2 = new DependentObject2();
        }
        
        public function setData($do1, $do2)
        {
            $this->data1->setData($do1);
            $this->data2->setData($do2);
        }
        
        public function getData()
        {
            return [
                $this->data1->getData(),
                $this->data2->getData(),
            ];
        }
    }
    
    class CompositeEntity
    {
        private $cgo = null;
        
        public function __construct()
        {
            $this->cgo = new CoarseGrainedObject();
        }
        public function setData($data1, $data2)
        {
            $this->cgo->setData($data1, $data2);
        }
        
        public function getData()
        {
            return $this->cgo->getData();
        }
    }
    
    class Client
    {
        private $compositeEntity = null;
        
        public function __construct()
        {
            $this->compositeEntity = new CompositeEntity();
        }
        public function printData()
        {
            $getData = $this->compositeEntity->getData();
            $getDataLen = count($getData);
            for ($i = 0; $i < $getDataLen; $i++) {
             echo "Data: " . $getData[$i];
            }
        }
        
        public function setData($data1, $data2)
        {
            $this->compositeEntity->setData($data1, $data2);
        }
    }
    
    $Client = new Client();
    $Client->setData("Test", "Data");
    $Client->printData();
    $Client->setData("Second Test", "Data1");
    $Client->printData();
    

    参考文章 http://www.runoob.com/design-pattern/composite-entity-pattern.html

    相关文章

      网友评论

          本文标题:组合实体模式

          本文链接:https://www.haomeiwen.com/subject/rlglfxtx.html