1、享元模式提出
面向对象很好地解决了抽象问题,但是创建对象会带来一定的内存开销。绝大部分情况下,创建对象带来的内存开销是可以忽略不计的;在有些情况下是需要谨慎处理的,如类A的sizeof是50个字节,则创建50*1024*100个A对象,则对象的内存大小约为5MB,这个是很占用内存的。享元模式就是使用运用共享技术支持创建大量的对象情况,并同时减少内存开销。
2、需求描述
有3种类型产品,这几种类型产品的形状和大小各不相同;现有1000个产品(3种类型),分别输出这些产品的类型和大小。
3、享元模式的代码实现
#include <iostream>
#include <string>
#include <map>
#include <vector>
namespace FlyWeight {
const std::string strG1="G1";
const std::string strG2="G2";
const std::string strG3="G3";
class AbsProduct
{
public:
    virtual void Shape()=0;
    virtual void Size()=0;
    std::string m_strType;
    virtual ~AbsProduct(){};
};
class ProductA:public AbsProduct
{
public:
    virtual void Shape()
    {
        std::cout << "rectangle" << std::endl;
    };
    virtual void Size()
    {
        std::cout << "60*60" << std::endl;
    };
};
class ProductB:public AbsProduct
{
public:
    virtual void Shape()
    {
        std::cout << "triangle" << std::endl;
    };
    virtual void Size()
    {
        std::cout << "30*40*50" << std::endl;
    };
};
class ProductC:public AbsProduct
{
public:
    virtual void Shape()
    {
        std::cout << "polygon" << std::endl;
    };
    virtual void Size()
    {
        std::cout << "30*40*50*60*60" << std::endl;
    };
};
class ProductFact
{
 private:
    std::map<std::string,AbsProduct*>mapProduts;
public:
    AbsProduct* GetProduct(std::string strType)
    {
        auto it = mapProduts.find(strType);
        if(it != mapProduts.end())
        {
            return it->second;
        }else
        {
            AbsProduct* newProduct = nullptr;
          if(strG1 == strType)
          {
              newProduct = new ProductA();
          }else if(strG2 == strType)
          {
              newProduct = new ProductB();
          }else
          {
              newProduct = new ProductC();
          }
               mapProduts[strType] = newProduct;
               return newProduct;
        }
    };
void clear()
{
    for(auto it = mapProduts.begin(); it != mapProduts.end(); it++)
    {
        delete (it->second);
        it->second = nullptr;
    }
}
};
}
std::vector<std::string>vecProducts;
int main()
{
    for(int i = 0; i < 1000* 1; i++)
    {
        if(i % 3 == 0)
        {
            vecProducts.emplace_back(FlyWeight::strG1);
        }else if(i % 3 == 1)
        {
            vecProducts.emplace_back(FlyWeight::strG2);
        }else{
            vecProducts.emplace_back(FlyWeight::strG3);
        }
    }
    FlyWeight::ProductFact obj;
    for(auto it = vecProducts.begin(); it != vecProducts.end();it++)
    {
        std::cout << "\n";
        FlyWeight::AbsProduct *objIter= obj.GetProduct(*it);
        std::cout << objIter << std::endl;
        objIter->Size();
        objIter->Shape();
    }
    obj.clear();
    vecProducts.clear();
    return 0;
}
运行结果如下:








![[LeetCode]矩阵对角线元素的和](https://img-blog.csdnimg.cn/3eab16098fcb49e6826fa3cbbdcc7960.png)









![[oneAPI] 手写数字识别-VAE](https://img-blog.csdnimg.cn/6adeb56f69d64b58b8500377f5b0850a.png)

