xxxxxxxxxx
public final class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}
xxxxxxxxxx
A singleton is a design pattern in software engineering that restricts
a class to have only one instance of the object and provides a single
point of access to it for any part of the code. The purpose of the
singleton pattern is to ensure that a class has only one instance
and to provide a global point of access to this instance.
In other words, it is a class that is designed to have only one instance
and to ensure that this instance is easily accessible to the rest of the system.
Singleton classes are often used for things like database connections,
logging, thread pools, or caches, where having multiple instances could
lead to unexpected behavior or errors.
xxxxxxxxxx
let instance;
let counter = 0;
class Counter {
constructor() {
if (instance) {
throw new Error("You can only create one instance!");
}
instance = this;
}
}
const singletonCounter = Object.freeze(new Counter());
export default singletonCounter;
xxxxxxxxxx
class SingletonExample
{
private static $instance;
// Prevent instantiation of the class through the constructor
private function __construct()
{
// Initialize object properties here, if needed
}
// Static method to get the unique instance
public static function getInstance()
{
if (!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
// Add specific methods of your singleton here
public function someMethod()
{
// Your code here
}
}
$singleton1 = SingletonExample::getInstance();
$singleton2 = SingletonExample::getInstance();
// Both $singleton1 and $singleton2 refer to the same instance
// You will have only one instance of SingletonExample throughout the system.