设计模式-享元模式

本文介绍了一种用于节省内存开销的设计模式——享元模式,并通过具体实现展示了如何使用共享和非共享享元对象来减少资源消耗。代码示例涵盖了享元接口、工厂类及其实现细节。

适用情境:需要大量共享对象,以节省内存开销.

这里写图片描述

// flyweight.h
#ifndef FLYWEIGHT_H
#define FLYWEIGHT_H

class Flyweight
{
public:
    virtual void Show() = 0;
};

#endif // FLYWEIGHT_H
// sharedflyweight.h
#ifndef SHAREDFLYWEIGHT_H
#define SHAREDFLYWEIGHT_H

#include "flyweight.h"
#include <string>

class SharedFlyweight : public Flyweight
{
public:
    SharedFlyweight(std::string name);
    virtual void Show();
private:
    std::string m_name;
};

#endif // SHAREDFLYWEIGHT_H
// sharedflyweight.cpp
#include "sharedflyweight.h"
#include <iostream>

SharedFlyweight::SharedFlyweight(std::__cxx11::string name)
{
    m_name = name;
}

void SharedFlyweight::Show()
{
    std::cout << "name : " << m_name << std::endl;
}
// unsharedflyweight.h
#ifndef UNSHAREDFLYWEIGHT_H
#define UNSHAREDFLYWEIGHT_H

#include "flyweight.h"
#include <string>

class UnsharedFlyweight : public Flyweight
{
public:
    UnsharedFlyweight(std::string name);
    virtual void Show();
private:
    std::string m_name;
};

#endif // UNSHAREDFLYWEIGHT_H
// unsahredflyweight.cpp
#include "unsharedflyweight.h"
#include <iostream>

UnsharedFlyweight::UnsharedFlyweight(std::string name)
{
    m_name = name;
}

void UnsharedFlyweight::Show()
{
    std::cout << "name : " << m_name << std::endl;
}
// flyweightfactory.h
#ifndef FLYWEIGHTFACTORY_H
#define FLYWEIGHTFACTORY_H

#include "flyweight.h"
#include <vector>

class FlyweightFactory
{
public:
    std::vector<Flyweight*> m_flyweightList;
public:
    FlyweightFactory();
    Flyweight* GetFlyweight();
};

#endif // FLYWEIGHTFACTORY_H
// flyweightfactory.cpp
#include "flyweightfactory.h"
#include "sharedflyweight.h"

FlyweightFactory::FlyweightFactory()
{
    m_flyweightList.push_back(new SharedFlyweight(" shared flyweight test"));
}

Flyweight* FlyweightFactory::GetFlyweight()
{
    std::vector<Flyweight*>::iterator it = m_flyweightList.begin();
    return (*it);
}

客户端:

// main.cpp
#include <iostream>
#include "sharedflyweight.h"
#include "flyweightfactory.h"
#include "unsharedflyweight.h"

using namespace std;

int main(int argc, char *argv[])
{
    FlyweightFactory* flyweight_factory = new FlyweightFactory();
    Flyweight* shared_flyweight = flyweight_factory->GetFlyweight();

    Flyweight* unshare_flyweight = new UnsharedFlyweight("unshare flyweight");

    shared_flyweight->Show();
    unshare_flyweight->Show();

    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值