Junior — Middle
Can you explain what is meant by creational patterns in software development?
sobes.tech AI
Answer from AI
Creational design patterns are templates that help create objects in a specific way, simplifying and standardizing the creation process. They hide the complexity of instantiation and allow flexible management of object creation.
Main creational patterns:
- Singleton — ensures that a class has only one instance.
- Factory Method — defines an interface for creating an object but allows subclasses to alter the type of objects that will be created.
- Abstract Factory — provides an interface for creating families of related or dependent objects without specifying their concrete classes.
- Builder — separates the construction of a complex object from its representation.
- Prototype — creates new objects by copying existing ones.
Example in Python, Factory Method:
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof"
class Cat(Animal):
def speak(self):
return "Meow"
class AnimalFactory:
@staticmethod
def create_animal(animal_type):
if animal_type == "dog":
return Dog()
elif animal_type == "cat":
return Cat()
else:
return None
animal = AnimalFactory.create_animal("dog")
print(animal.speak()) # Outputs: Woof
Thus, creational patterns simplify object creation and make the code more flexible and maintainable.