Design Patterns in Action(3)- Singleton

A series of programming design patterns illustration with examples with JavaScript/Python

Photo by Pesce Huang on Unsplash

Creational Pattern — Singleton

class BreadSingleton:

__instance = None

def __init__(self):
if BreadSingleton.__instance:
raise Exception(
"An instance already been initiated !")
else:
BreadSingleton.__instance = self

def bake_bread(self, quantity, name):
self.quantity = quantity
self.name = name

def put_on_shelf(self):
print(f"{self.quantity} of {self.name} are put on shelf!")

@staticmethod
def getInstance():
if not BreadSingleton.__instance:
BreadSingleton()
return BreadSingleton.__instance


oven1 = BreadSingleton.getInstance()
oven1.bake_bread(5, "sourDough")
oven1.put_on_shelf()

oven2 = BreadSingleton.getInstance()
oven2.bake_bread(10, "ciabatta")
oven2.put_on_shelf()

print(oven1 == oven2)
===
5 of sourDough are put on shelf!
10 of ciabatta are put on shelf!
True
import threadingclass BreadSingletonTwo:

__singleton_lock = threading.Lock()
__instance = None

def __init__(self):
if not BreadSingletonTwo.__instance:
with BreadSingletonTwo.__singleton_lock:
if not BreadSingletonTwo.__instance:
BreadSingletonTwo.__instance = self
else:
raise Exception(
"An instance already been initiated !")

def bake_bread(self, quantity, name):
self.quantity = quantity
self.name = name

def put_on_shelf(self):
print(f"{self.quantity} of {self.name} are put on shelf!")

@staticmethod
def get_instance():
if not BreadSingletonTwo.__instance:
BreadSingletonTwo()
return BreadSingletonTwo.__instance
class BreadOven {
constructor() {
this._startOven = true;
}
bake_bread(quantity, name) {
this.quantity = quantity;
this.name = name;
}
put_on_shelf() {
return `${this.quantity} of ${this.name} are put on shelf!`;
}
}

const BreadSingleton = (function () {
let breadInstance;

return {
getInstance: function () {
if (!breadInstance) {
breadInstance = new BreadOven();
delete breadInstance.constructor;
}
return breadInstance;
},
};
})();

let oven1 = BreadSingleton.getInstance();
oven1.bake_bread(5, "sourDough");
oven1.put_on_shelf();

let oven2 = BreadSingleton.getInstance();
oven2.bake_bread(10, "ciabatta");
oven2.put_on_shelf();
Oven.jsclass BreadSingletonTwo {
constructor() {
if (!BreadSingletonTwo.instance) {
this._oven = new BreadOven();
BreadSingletonTwo.instance = this;
}

return BreadSingletonTwo.instance;
}

bake_bread(quantity, name) {
return this._oven.bake_bread(quantity, name);
}
put_on_shelf() {
return this._oven.put_on_shelf();
}
}

const oven = new BreadSingletonTwo();
Object.freeze(oven);
export default oven;=======================>import oven from "./Oven"oven.bake_bread(10, "ciabatta");
oven.put_on_shelf();

Hi :)