本文摘自网络,作者黄舟,侵删。
享元模式(Flyweight):运用共享技术有效地支持大量细粒度的对象。
四个角色类:
Flyweight享元类:所有具体享元类的超类或接口,通过这个接口,Flyweight可以接受并作用于外部状态。
Flyweight享元工厂类:一个享元工厂,用来创建并管理Flyweight,当用户请求一个Flyweight时,FlyweightFactory对象提供一个已创建的实例或者创建一个(如果不存在的话)。
ConcreteFlyweight具体享元类:继承Flyweight超类或实现Flyweight接口,并为内部状态增加存储空间。
UnSharedConcreteFlyweight不需共享的具体Flyweight子类、指那些不需要共享的Flyweight子类。因为Flyweight接口类共享成为可能,但并不强制共享。
模式实现:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | [code]
class Flyweight{
public :
virtual void Operation( int extrinsicState){}
};
class ConcreteFlyweight: public Flyweight{
public :
virtual void Operation( int extrinsicState)override{
std::cout << "ConcreteFlyweight: " << extrinsicState << std::endl;
}
};
class UnSharedConcreteFlyweight: public Flyweight{
public :
virtual void Operation( int extrinsicState){
std::cout << "UnSharedConcreteFlyweight: " << extrinsicState << std::endl;
}
};
class FlyweightFactory{
private :
std::map<std::string, Flyweight*> flyweights;
public :
FlyweightFactory(){
flyweights[ "X" ] = new ConcreteFlyweight;
flyweights[ "Y" ] = new ConcreteFlyweight;
flyweights[ "Z" ] = new ConcreteFlyweight;
}
Flyweight* GetFlyweight(std::string key){
return (Flyweight*)flyweights[key];
}
};
|
客户端:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | [code]
int main(){
int extrinsicState = 22;
FlyweightFactory *f = new FlyweightFactory;
Flyweight* fx = f->GetFlyweight( "X" );
fx->Operation(--extrinsicState);
Flyweight* fy = f->GetFlyweight( "Y" );
fy->Operation(--extrinsicState);
Flyweight* fz = f->GetFlyweight( "Z" );
fz->Operation(--extrinsicState);
Flyweight *uf = new UnSharedConcreteFlyweight;
uf->Operation(--extrinsicState);
return 0;
}
|
享元模式好处:
如果一个应用程序使用了大量的对象,而大量的这些对象造成了很大的存储开销时就应该考虑使用。
对象的大多数状态可以使用外部状态,如果删除对象的外部状态,那么可以用相对较少的共享对象取代很多组对象,此时可以考虑使用享元模式。
以上就是C++设计模式浅识享元模式的内容,更多相关内容请关注PHP中文网(www.php.cn)!
相关阅读 >>
c++设计模式浅识享元模式
更多相关阅读请进入《C++,设计模式,享元模式》频道 >>
转载请注明出处:木庄网络博客 » C++设计模式浅识享元模式