---
# System prepended metadata

title: Factory method
tags: [design-patterns]

---

# Factory method

###### tags: `design-patterns`

[https://refactoring.guru/design-patterns/factory-method](https://refactoring.guru/design-patterns/factory-method)

[https://realpython.com/factory-method-python/](https://realpython.com/factory-method-python/)

### Overview

Factory Method is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.

### Code

```python=
class Extra:
    def get_details(self):
        pass

class FactoryClassNotFound(Exception):
    pass

class ProcessFactory:
    def __init__(self):
        self._processes = {}

    def register_process(self, source, process):
        self._processes[source] = process

    def get_process(self, source) -> ProcessBase:
        process = self._processes.get(source)
        
        if not process:
            raise FactoryClassNotFound(source)
        
        return process()

class ProcessBase():
    def get_extra(self) -> Extra:
        raise NotImplementedError()
    
    def finish_processing(self):
        raise NotImplementedError()

class ManualOffer(ProcessBase):
    def get_extra(self) -> Extra:
        pass
    
    def finish_processing(self):
        pass

class PriorityBoarding(ProcessBase):
    def get_extra(self) -> Extra:
        pass

    def finish_processing(self):
        pass

process_factory = ProcessFactory()
process_factory.register_process('portalo', ManualOffer)
process_factory.register_process('ancillaries', PriorityBoarding)

def handle_extra(request):
    try:
        process_class = process_factory.get_process(request.source)
    except FactoryClassNotFound:
        raise HTTPError('Unknow source of request')

    process = process_class()

    extra_item = process.get_extra()

    await process.finish_process()
```