Design Pattern --- FlyWeight

struct Context
{
    int x, y;
};

class FlyWeight
{
    // data.
    const string m_str;

public:
    FlyWeight(const string &str) : m_str(str) {}
public:
    // Interface.
    void draw(Context &c) 
    {
        cout <<c.x <<" : " <<c.y <<" => " <<m_str <<endl;
    }
};

int main(int argc, char *argv[])
{
    Context c1 = {4, 8}, c2 = {0, -4}, c3 = {-1, 2}, c4 = {9, 2};
    FlyWeight f1("abcdefg"), f2("12345678");                        // 这里只有两个字符串对象, 这是稳定的内容. 但是可以和很多个表示易变信息的 Context 对象组合在一起, 
                                                                    // 而不必每个 Context 都有相同的字符串. 因此节省了内存.

    f1.draw(c1);
    f1.draw(c2);
    f1.draw(c3);

    f2.draw(c1);
    f2.draw(c2);
    f2.draw(c3);
    f2.draw(c4);

    return 0;
}

FlyWeight 的优势在于有非常多的对象都拥有共同的数据成员. 这种情况下我们就可以通过抽象, 将易变部分提取出来. 这就是 FlyWeight 的意图.
设计模式的核心思想就是, 分离和封装变化.

转载于:https://www.cnblogs.com/walfud/articles/2880885.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值