在软件系统中,采用纯粹对象方案的问题在于大量的细粒度的对象会很快充斥在系统中,从而带来很高的运行时代价—主要指内存需求方面的代价。
优点
- 运用共享技术有效地支持大量细粒度的对象。
- 面向对象很好地解决了抽象性的问题,但是作为一个运行在机器中的程序实体,我们需要考虑对象的代价问题。Flyweight主要解决面向对象的代价问题,一般不触及面向对象的抽象性问题。
- Flyweight采用对象共享的做法来降低系统中对象的个数,从而降低细粒度对象给系统带来的内存压力。在具体实现方面,要注意对象状态的处理。
代码如下
Flyweight.h文件
#pragma once
#include<string>
using namespace std;
class Flyweight {
public:
virtual ~Flyweight();
virtual void operation(const string& extrastr);
string getInstr();
protected:
Flyweight(const string& instr);
private:
string instr;
};
class ConcreteFlyweight :public Flyweight {
public:
~ConcreteFlyweight();
ConcreteFlyweight(const string& instr);
void operation(const string& extrastr);
};
Flyweight.cpp
#include<iostream>
#include"Flyweight.h"
using namespace std;
Flyweight::Flyweight(const string& instr) {
this->instr = instr;
}
Flyweight::~Flyweight() {
}
void Flyweight::operation(const string& extrastr) {
}
string Flyweight::getInstr() {
return this->instr;
}
ConcreteFlyweight::ConcreteFlyweight(const string& instr) :Flyweight(instr) {
cout << "ConcreteFlyweight build string " << instr << endl;
}
ConcreteFlyweight::~ConcreteFlyweight() {
}
void ConcreteFlyweight::operation(const string& extrastr) {
cout << "ConcreteFlyweight: 内 蕴[" << this->getInstr() << "] 外 蕴[" << extrastr << "]" << endl;
}
FlyweightFactory.h
#pragma once
#include"Flyweight.h"
#include<vector>
#include<string>
class FlyweightFactory {
public:
~FlyweightFactory();
FlyweightFactory();
Flyweight* operation(const string& str);
private:
vector<Flyweight*> v;
};
FlyweightFactory.cpp
#include"FlyweightFactory.h"
#include<iostream>
using namespace std;
FlyweightFactory::FlyweightFactory() {
}
FlyweightFactory::~FlyweightFactory() {
}
Flyweight* FlyweightFactory::operation(const string& str) {
vector<Flyweight*>::iterator it = v.begin();
for (; it != v.end(); it++) {
if ((*it)->getInstr() == str) {
cout << "already created" << endl;
return *it;
}
}
Flyweight* fly = new ConcreteFlyweight(str);
v.push_back(fly);
return fly;
}
Main.cpp
#include"Flyweight.h"
#include"FlyweightFactory.h"
#include<iostream>
using namespace std;
int main() {
FlyweightFactory* fac = new FlyweightFactory();
Flyweight* fw1 = fac->operation("hello");
Flyweight* fw2 = fac->operation("llll");
Flyweight* fw3 = fac->operation("hello");
return 0;
}
结果运行如下