const Singleton = (function () {
let instance;
function Singleton() {
if (instance) {
throw new Error("Singleton instance already exists. Use getInstance method.");
}
this.data = Math.random();
}
Singleton.getInstance = function () {
if (!instance) {
instance = new Singleton();
}
return instance;
};
Singleton.prototype.clone = function () {
throw new Error("Cloning of singleton instance is not allowed.");
};
Singleton.prototype.customDeserialize = function () {
throw new Error("Deserialization of singleton instance is not allowed.");
};
function revive(key, value) {
if (key === '' && value && value.__isSingleton) {
return instance;
}
return value;
}
Singleton.prototype.toJSON = function () {
return JSON.stringify({ __isSingleton: true, data: this.data });
};
return Singleton;
})();
try {
const singletonInstance1 = Singleton.getInstance();
console.log(singletonInstance1);
const singletonInstance2 = new Singleton();
} catch (error) {
console.error(error.message);
}
try {
const clonedInstance = Object.create(singletonInstance1);
console.log(clonedInstance);
} catch (error) {
console.error(error.message);
}
try {
const serializedInstance = JSON.stringify(singletonInstance1);
console.log(serializedInstance);
} catch (error) {
console.error(error.message);
}
const jsonString = JSON.stringify(singletonInstance1);
const deserializedInstance = JSON.parse(jsonString, revive);
console.log(deserializedInstance);