brief introduction

Sharing technology is used to effectively support the reuse of a large number of fine-grained objects.

Advantage

Because there is no need to recreate the object, the overhead of initializing the object is reduced, the running speed is improved, and the memory consumption of new object is also reduced.
Because of reusing objects, the amount of code and the complexity of the system are reduced.

Usage scenarios

When an application uses a large number of objects, most of the state of the objects can be changed to external state.

The code is as follows:

#include <iostream>
#include <string>
#include <memory>
#include <map>


class flyweight 
{
public:
	flyweight(std::string key) : m_key(key)
	{
	}
 
	virtual void operate(int value)
	{
		std::cout << "flyweight::operate : m_key["<< m_key <<"] value[" << value << "] ."<< std::endl;
	}
 
private:
	std::string m_key;
};
 

class flyweight_factory
{
public:
	flyweight_factory(void)
	{
	}
 
	~flyweight_factory(void)
	{
		std::map<std::string, flyweight *>::iterator it;
		for (it = m_flymap.begin(); it != m_flymap.end(); it++)
		{
			if (it->second != NULL)
			{
				delete it->second;
				it->second = NULL;
			}
		}
	}
	
public:
	flyweight *get_flyweight(std::string key)
	{
		std::map<std::string, flyweight *>::iterator it = m_flymap.find(key);
		if (it != m_flymap.end())
		{
			return it->second;
		}
	 
		flyweight * fly = new flyweight(key);
		m_flymap.insert(std::map<std::string, flyweight *>::value_type(key, fly));
	 
		return fly;
	}

private:
	std::map<std::string, flyweight *> m_flymap;
};

int main()
{
	std::cout << "start-up .." << std::endl;
	
	
	std::shared_ptr<flyweight_factory>  ff = std::make_shared<flyweight_factory>();
 
	flyweight * f1 = ff->get_flyweight("lanpang");
	flyweight * f2 = ff->get_flyweight("naja");
	flyweight * f3 = ff->get_flyweight("lanpang");
	flyweight * f4 = ff->get_flyweight("lanpang");
 
	f1->operate(100);
	
	f2->operate(111);
	
	f3->operate(133);
 
	f4->operate(200);

	std::cout << "done .." << std::endl;
    return 0;
}


The operation is as follows: