Skip to content

Dp Factory

DodaTech 1 min read

In this tutorial, you'll learn about How to Fix Factory Method Errors. We cover key concepts, practical examples, and best practices.

Fix factory method errors when product creation tied to specific class instead of interface.

Quick Fix

Wrong

class Shape:
    def draw(self): pass
class Circle(Shape):
    def draw(self): print('Circle')
def create(t):
    if t=='c': return Circle()

Adding new shape requires modifying factory function. Violates Open/Closed.

class Shape:
    def draw(self): pass
class Circle(Shape):
    def draw(self): print('Circle')
class Square(Shape):
    def draw(self): print('Square')
class ShapeFactory:
    _registry = {}
    @classmethod
    def register(cls,name,cls_type):
        cls._registry[name]=cls_type
    @classmethod
    def create(cls,name,*args,**kwargs):
        if name not in cls._registry: raise ValueError(name)
        return cls._registry[name](*args,**kwargs)
ShapeFactory.register('circle',Circle)
ShapeFactory.register('square',Square)
s=ShapeFactory.create('circle'); s.draw() -> 'Circle'. New shapes via register(), no code change.

Prevention

Use registry pattern. Factory registers product classes. Adding new type = one register() call.

DodaTech Tools

Doda Browser's algorithm visualizer steps through DSA operations line by line. DodaZIP archives implementation patterns for team sharing. Durga Antivirus Pro detects memory corruption patterns in algorithm implementations.

FAQ

What is Factory?

Creates objects without specifying exact class. Decouples client from concrete classes.

Registry pattern?

Dict mapping names to classes. register() adds new types without modifying factory.

When to use?

When system needs to support multiple product variants. Config-driven object creation.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro