xxxxxxxxxx
public class Singleton {
private static Singleton instance;
private Singleton() { }
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
xxxxxxxxxx
Singleton:
The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance.
Example in ReactJS:
You might want to create a settings manager that's accessible from any component.
// SingletonSettings.js
let instance = null;
const SingletonSettings = () => {
if (!instance) {
instance = {
theme: 'light',
fontSize: '16px',
};
}
return instance;
};
// Usage
const settings = SingletonSettings();
console.log(settings.theme); // Outputs 'light'
// In another component
const otherComponentSettings = SingletonSettings();
console.log(otherComponentSettings.fontSize); // Outputs '16px'
xxxxxxxxxx
class Singleton(object):
__instance = None
def __new__(cls, *args):
if cls.__instance is None:
cls.__instance = object.__new__(cls, *args)
return cls.__instance
xxxxxxxxxx
public sealed class Singleton
{
private static readonly Lazy<Singleton> instance = new Lazy<Singleton>(() => new Singleton());
private Singleton()
{
// Private constructor to prevent external instantiation
}
public static Singleton Instance => instance.Value;
public void SomeMethod()
{
// Perform some action
}
}