Flyweight(享元模式)

在软件系统中,采用纯粹对象方案的问题在于大量的细粒度的对象会很快充斥在系统中,从而带来很高的运行时代价—主要指内存需求方面的代价。
优点

  • 运用共享技术有效地支持大量细粒度的对象。
  • 面向对象很好地解决了抽象性的问题,但是作为一个运行在机器中的程序实体,我们需要考虑对象的代价问题。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;
}

结果运行如下
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值