学习高校课程-软件设计模式-单例模式(lec5)
Singleton: Intent
Singleton is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance.
Singleton 是一种创建性设计模式,它允许您确保一个类只有一个实例,同时提供对此实例的全局访问点。
Singleton: solves two problems
1.Ensure that a class has just a single instance
确保一个类只有一个实例
Why would anyone want to control how many instances a class has? The most common reason for this is to control access to some shared resource—for example, a database or a file.
为什么有人想要控制一个类有多少个实例呢?最常见的原因是控制对某些共享资源(例如,数据库或文件)的访问。
2.Provide a global access point to that instance.
提供该实例的全局访问点
Just like a global variable, the Singleton pattern lets you access some object from anywhere in the program. However, it also protects that instance from being overwritten by other code.
就像全局变量一样,Singleton 模式允许您从程序中的任何位置访问某些对象。但是,它还可以保护该实例不被其他代码覆盖。
Singleton: Solution
1.Make the default constructor private, to prevent other objects from using the new operator with the Singleton class.
将默认构造函数设为 private,以防止其他对象将 new 运算符与 Singleton 类一起使用。
2.Create a static creation method that acts as a constructor. Under the hood, this method calls the private constructor to create an object and saves it in a static field. All following calls to this method return the cached object.
创建充当构造函数的静态创建方法。在后台,此方法调用私有构造函数来创建对象并将其保存在 static 字段中。对此方法的所有后续调用都将返回缓存的对象。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战