C++设计模式浅识享元模式


本文摘自网络,作者黄舟,侵删。

享元模式(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;

    }

};

 

//不需共享的Flyweight子类

class UnSharedConcreteFlyweight: public Flyweight{

public:

    virtual void Operation(int extrinsicState){

        std::cout << "UnSharedConcreteFlyweight: " << extrinsicState << std::endl;

    }

};

 

//享元工厂,用来创建并管理Flyweight对象

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]//Client

int main(){

    //外部状态

    int extrinsicState = 22;

    //工厂

    FlyweightFactory *f = new FlyweightFactory;

    Flyweight* fx = f->GetFlyweight("X");

    fx->Operation(--extrinsicState);  //Output: ConcreteFlyweight: 21

 

    Flyweight* fy = f->GetFlyweight("Y");

    fy->Operation(--extrinsicState);  //Output: ConcreteFlyweight: 20

 

    Flyweight* fz = f->GetFlyweight("Z");

    fz->Operation(--extrinsicState);  //Output: ConcreteFlyweight: 19

 

    Flyweight *uf = new UnSharedConcreteFlyweight;  //Output: UnSharedConcreteFlyweight: 18

    uf->Operation(--extrinsicState);

 

    return 0;

}

享元模式好处:

如果一个应用程序使用了大量的对象,而大量的这些对象造成了很大的存储开销时就应该考虑使用。

对象的大多数状态可以使用外部状态,如果删除对象的外部状态,那么可以用相对较少的共享对象取代很多组对象,此时可以考虑使用享元模式。

以上就是C++设计模式浅识享元模式的内容,更多相关内容请关注PHP中文网(www.php.cn)!


相关阅读 >>

c++设计模式浅识享元模式

更多相关阅读请进入《C++,设计模式,享元模式》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...