单例模式的C++实现

  1. 单例模式在实际应用中有很大的使用。widows系统的任务管理器就是一个单例。
  2. 单例模式的主要使用场景在于所有对象都访问唯一实例。便于进行一些重要的操作。
  3. #include
    #include
    #include
    using namespace std;
    class Shape//定义一个基类,便于后面验证单例模式。
    {
    public:
    virtual void display() = 0;
    virtual string name() = 0;
    };
    class Chang:public Shape//继承基类
    {
    public:
    Chang(string n)
    {
    this->name_ = n;
    }
    void display()
    {
    cout << “this is Chang” << endl;
    }
    string name() override
    {
    return name_;
    }
    private:
    string name_;
    };
    class Duan :public Shape//继承基类
    {
    public:
    Duan(string n)
    {
    this->name_ = n;
    }
    void display()
    {
    cout << “this is Duan” << endl;
    }
    string name() override
    {
    return name_;
    }
    private:
    string name_;
    };
    class Fang :public Shape//继承基类
    {
    public:
    Fang(string n)
    {
    this->name_ = n;
    }
    void display()
    {
    cout << “this is Fang” << endl;
    }
    string name() override
    {
    return name_;
    }
    private:
    string name_;
    };
    class Factory
    {
    public:
    static Factory *instance()//定义一个函数,用来获得单例的唯一实例
    {
    if (instance_ == nullptr)//为空时创建,否则直接返回已经创建好的类。
    {
    instance_ = new Factory();
    }
    return instance_;
    }
    bool addShape(Shape *s)
    {
    if (!shapeMap[s->name()])//map中不存在该类的指针,则更新map
    {
    shapeMap[s->name()] = s;
    return true;
    }
    return false;
    }
    map<string, Shape *> getShapeMap()
    {
    return shapeMap;
    }
    private:
    static Factory * instance_;
    map<string, Shape *> shapeMap;//定义一个map,用来存储各个以shap为基类的实例化的类
    };
    Factory * Factory::instance_ = nullptr;//类的static变量,使用前要初始化。赋值为空。
    int main()
    {
    auto f = Factory::instance();//获得类的单实例
    f->addShape(new Fang(“Fang”));
    f->addShape(new Duan(“Duan”));
    f->addShape(new Chang(“Chang”));
    f->addShape(new Chang(“Chang”));//干扰项
    auto f1 = Factory::instance();获得类的单实例
    auto shapemap = f1->getShapeMap();
    for (auto x : shapemap)
    {
    cout << x.first << endl;
    x.second->display();
    }
    system(“pause”);
    return 0;
    }
    验证结果如下图所示:
    在这里插入图片描述
    通过单实例,我们可以把一个类在系统中只保留一份,节省了存储空间
    ,而且每次使用的时候单例里面的数据不用再从外面进行加载或者重新运算。提高了访问的速度。是非常好用的一个模式啊。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值