适用情境:需要大量共享对象,以节省内存开销.
// flyweight.h
#ifndef FLYWEIGHT_H
#define FLYWEIGHT_H
class Flyweight
{
public:
virtual void Show() = 0;
};
#endif // FLYWEIGHT_H
// sharedflyweight.h
#ifndef SHAREDFLYWEIGHT_H
#define SHAREDFLYWEIGHT_H
#include "flyweight.h"
#include <string>
class SharedFlyweight : public Flyweight
{
public:
SharedFlyweight(std::string name);
virtual void Show();
private:
std::string m_name;
};
#endif // SHAREDFLYWEIGHT_H
// sharedflyweight.cpp
#include "sharedflyweight.h"
#include <iostream>
SharedFlyweight::SharedFlyweight(std::__cxx11::string name)
{
m_name = name;
}
void SharedFlyweight::Show()
{
std::cout << "name : " << m_name << std::endl;
}
// unsharedflyweight.h
#ifndef UNSHAREDFLYWEIGHT_H
#define UNSHAREDFLYWEIGHT_H
#include "flyweight.h"
#include <string>
class UnsharedFlyweight : public Flyweight
{
public:
UnsharedFlyweight(std::string name);
virtual void Show();
private:
std::string m_name;
};
#endif // UNSHAREDFLYWEIGHT_H
// unsahredflyweight.cpp
#include "unsharedflyweight.h"
#include <iostream>
UnsharedFlyweight::UnsharedFlyweight(std::string name)
{
m_name = name;
}
void UnsharedFlyweight::Show()
{
std::cout << "name : " << m_name << std::endl;
}
// flyweightfactory.h
#ifndef FLYWEIGHTFACTORY_H
#define FLYWEIGHTFACTORY_H
#include "flyweight.h"
#include <vector>
class FlyweightFactory
{
public:
std::vector<Flyweight*> m_flyweightList;
public:
FlyweightFactory();
Flyweight* GetFlyweight();
};
#endif // FLYWEIGHTFACTORY_H
// flyweightfactory.cpp
#include "flyweightfactory.h"
#include "sharedflyweight.h"
FlyweightFactory::FlyweightFactory()
{
m_flyweightList.push_back(new SharedFlyweight(" shared flyweight test"));
}
Flyweight* FlyweightFactory::GetFlyweight()
{
std::vector<Flyweight*>::iterator it = m_flyweightList.begin();
return (*it);
}
客户端:
// main.cpp
#include <iostream>
#include "sharedflyweight.h"
#include "flyweightfactory.h"
#include "unsharedflyweight.h"
using namespace std;
int main(int argc, char *argv[])
{
FlyweightFactory* flyweight_factory = new FlyweightFactory();
Flyweight* shared_flyweight = flyweight_factory->GetFlyweight();
Flyweight* unshare_flyweight = new UnsharedFlyweight("unshare flyweight");
shared_flyweight->Show();
unshare_flyweight->Show();
return 0;
}