设计模式之享元模式

享元模式运用共享技术有效地支持大量细粒度的对象。
如果一个应用程序使用了大量的对象,而大量的这些对象造成了很大的存储开销时应该考虑使用。对象的大多数状态可以是外部状态,如果删除对象的外部状态,那么可以用相对较少的共享对象取代很多组对象,此时也可以考虑用享元模式。
享元模式UML图如下:
这里写图片描述
代码如下:

//网站用户
class User
{
private:
    std::string m_strWebSiteUserName;
public:

    User(const std::string& __n)
    {
        m_strWebSiteUserName  = __n;
    }

    ~User() { }

    std::string GetUserName(void)
    {
        return m_strWebSiteUserName;
    }
};
class Website
{
protected:
    std::string m_strWebsiteName;
public:
    Website(const std::string& __u)
    {
        m_strWebsiteName = __u;
    }

     virtual ~Website()
    {
         //std::cout << "Website destructor" << std::endl;
    }

     virtual void Use(User* __u) {}
};

class ConcreteWebsite : public Website
{
public:
    ConcreteWebsite(const std::string& __u) : Website(__u) {}
    ~ConcreteWebsite() {}
    virtual void Use(User* __u) 
    {
        std::cout << "Web site classification:" << m_strWebsiteName << " User:" << __u->GetUserName()<<std::endl;
    }
};
class WebsiteFactory
{
private:
    std::map<std::string, Website*>  m_map;
public:
    WebsiteFactory() {}
    ~WebsiteFactory()
    {
        m_map.clear(); 
    }
    Website* GetWebsiteCategory(const std::string& key)
    {
        if (m_map.find(key) == m_map.end())
        {
            m_map[key] = new ConcreteWebsite(key);
        }
        return (m_map[key]);
    }

    size_t GetWebsiteCount()
    {
        return m_map.size();
    }

};
int _tmain(int argc, TCHAR* argv[])
{
    WebsiteFactory  fac;
    auto* pWebX = fac.GetWebsiteCategory("Product display");

    User uWang("WangDelong");
    pWebX->Use( &uWang);

    auto * pWebY = fac.GetWebsiteCategory("Paper display");

    User uYu("Yuyanyan");
    pWebY->Use(&uYu);

    std::cout << "Total catogary:" << fac.GetWebsiteCount() << std::endl;

    if (pWebX)
    {
        delete pWebX;
        pWebX = NULL;
    }

    if (pWebY)
    {
        delete pWebY;
        pWebY = NULL;
    }
    return 0;
}

运行结果如下:
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值