Loading the lesson...
In the print dialog, choose "Save as PDF" as the destination.
Singleton, Factory, and Builder
Singleton, Factory, BuildergetInstance() accessorclass DatabaseConnection:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance.connection = None
return cls._instance
def connect(self):
if self.connection is None:
self.connection = "Connected to Database"
return self.connection
db1 = DatabaseConnection()
db2 = DatabaseConnection()
print(db1 is db2) # True - Same instancecall DatabaseConnection()
is _instance None?
create it once
always return that same _instance
class Animal(ABC):
@abstractmethod
def make_sound(self): pass
class Dog(Animal):
def make_sound(self): return "Woof!"
class Cat(Animal):
def make_sound(self): return "Meow!"
class AnimalFactory:
@staticmethod
def create_animal(animal_type):
if animal_type == "dog":
return Dog()
elif animal_type == "cat":
return Cat()
dog = AnimalFactory.create_animal("dog")
print(dog.make_sound()) # Woof!Animal
abstract base
Dog
Cat
WindowsButton vs MacButton, chosen at runtime5+)class PizzaBuilder:
def __init__(self):
self.pizza = Pizza()
def set_size(self, size):
self.pizza.size = size
return self
def add_topping(self, topping):
self.pizza.toppings.append(topping)
return self
def build(self):
return self.pizza
pizza = (PizzaBuilder()
.set_size("Large")
.add_topping("Pepperoni")
.build()).set_size()
.add_topping()
.build()
Pizza object
Singleton: one instance, global access, but easy to abuse into global stateFactory: decouples object creation from usage, picks the class at runtimeBuilder: constructs complex objects step-by-step with a fluent, readable APISingleton for shared resources, Factory for type variability, Builder for many optional parametersMahmoud Abas|Part 1: Creational Design Patterns