码迷,mamicode.com
首页 > 其他好文 > 详细

享元模式很好的实例

时间:2015-11-27 14:57:20      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

<?php
/**
 * 享元模式
 *
 * 运用享元技术有效的支持大量细粒度的对象
 */
class CD
{
    private $_title = null;
    private $_artist = null;
    public function setTitle($title)
    {
        $this->_title = $title;
    }
    public function getTitle()
    {
        return $this->_title;
    }
    public function setArtist($artist)
    {
        $this->_artist = $artist;
        echo ‘打印参数传来的实例:‘.serialize($artist).‘<br>‘;
    }
    public function getArtist($artist)
    {
        return $this->_artist;
    }
}

class Artist
{
    private $_name;
    public function __construct($name)
    {
        echo "正在实例化:".$name."<br/>";
        $this->_name = $name;
    }
    public function getName()
    {
        return $this->_name;
    }
}

class ArtistFactory
{
    private $_artists = array();
    public function getArtist($name)
    {
        if(isset($this->_artists[$name]))//传过来的参数已经被实例化了,就返回参数对应的实例
        {
            return $this->_artists[$name];
        }
        else
        {
            $objArtist = new Artist($name);//实例化一个对象
            $this->_artists[$name] = $objArtist;//这个主要记录传过来的参数已经被实例化
            return $objArtist;//返回实例
        }
    }
}

//这里享元模式的研究对象是Artist类
$objArtistFactory = new ArtistFactory();
$objCD1 = new CD();
$objCD1->setTitle("title1");
$objCD1->setArtist($objArtistFactory->getArtist(‘artist1‘));
$objCD2 = new CD();
$objCD2->setTitle("title2");
$objCD2->setArtist($objArtistFactory->getArtist(‘artist2‘));
$objCD3 = new CD();
$objCD3->setTitle("title3");
$objCD3->setArtist($objArtistFactory->getArtist(‘artist1‘));//这个artist1对象已经存在,所以“正在实例化”那句不会输出

 

 

 

享元模式很好的实例

标签:

原文地址:http://www.cnblogs.com/jiufen/p/5000554.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!