C++设计模式--单例模式解析(head first 设计模式C++实现)

这篇博客介绍了单例模式的概念,即确保一个类只有一个实例并提供全局访问点。文中通过一个巧克力锅炉类的示例展示了如何在C++中实现单例模式,并强调了在多线程环境下需要对单例模式的调用进行同步,以防止竞态条件。博客还包含了一个简单的单例模式应用实例,展示其在模拟煮巧克力过程中的使用。
摘要由CSDN通过智能技术生成

单例模式

  1. 单例模式:确保一个类只有一个实例,并提供一个全局访问点
  2. 单例模式不一定适合设计进入一个库中。
  3. 确定性能和资源上的限制,然后小心地选择适当的方案来实现单件,在多线程程序中,对于调用单例模式,需要加锁,以解决多线程的问题。

例子

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RJGjvv31-1662710329230)(img/singinstance.png)]


   class ChocolateBoiler{

    public:
        static ChocolateBoiler* getInstance(){
            if(pointer==nullptr){
                pointer=new ChocolateBoiler;
            }
            return pointer;
        }

        void fill(){
            if(isEmpty()){
                cout<<" start fill"<<endl;
                empty=false;
                boiled=false;
            }
        }
        void drain(){
            if(!isEmpty()&&isBoiled()){
                cout<<" start drain"<<endl;
                boiled=false; 
                empty=true;
            }
        }

        void boil(){
            if(!isEmpty()&&!isBoiled()){
                cout<<" start boil"<<endl;
                boiled=true;
            }
        }

    private:
        ChocolateBoiler():empty(true),boiled(false){
            
        };
        bool empty;
        bool boiled;
        static ChocolateBoiler* pointer;
        bool isEmpty(){
            return empty;
        }
        bool isBoiled(){
            return boiled;
        }


};

ChocolateBoiler* ChocolateBoiler::pointer = nullptr;

int main(){

ChocolateBoiler::getInstance()->fill();//开始装
ChocolateBoiler::getInstance()->boil();//开始煮
ChocolateBoiler::getInstance()->drain();//开始排
cout<<endl; 
ChocolateBoiler::getInstance()->fill();
ChocolateBoiler::getInstance()->boil();
ChocolateBoiler::getInstance()->drain();

system("pause");
return 0;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值