jeudi 21 janvier 2021

Factory Implementation in Java

After a few years of coding in python, I recently moved to Java for a project. While working with Python, I had a pretty implementation for a factory.

# file abstract_product.py
from abc import ABC, abstractmethod
class AbstractProduct(ABC):
    @abstractmethod
    def do_something():
        pass
# file product_factory.py
from abstract_product import AbstractProduct

class ProductFactory:
    def __init__(self):
        self._creators = {}
    
    def get(self, product_name) -> Product:
        if product_name not in self._creators:
            raise ValueError('No valid implementation !')
        return self._creators[product_name]()
    
    def register(self, product_name, product):
        self._creators[product_name] = product

product_factory = ProductFactory()
# file product1.py
from abstract_product import AbstractProduct
from product_factory import product_factory

class Product1(AbstractProduct):
    def do_something():
        # does something
        pass

product_factory.register('product1', Product1)

Now the advantage would be, that if I had a new Implementation for Product, all I had to do was

# file product2.py
from abstract_product import AbstractProduct
from product_factory import product_factory

class Product2(AbstractProduct):
    def do_something():
        # does something
        pass

product_factory.register('product2', Product2)

The advantages of the above approach were:

  • I had my factory as a singleton. Defining the variable in module ensured that.
  • Registering a new Product, included no changes to the existing code.
  • No dirty if else ladder has to be set up any where!
  • The new implementation registered to the factory in their own module. SO CLEAN :D :D

All the client code needed to know was the product_factory from above and the string parameter based on which the client would get some implementation of Product.

However, now with Java, I am thinking what can I do, to get close to the simplicity and extensibility that the above approach had !

Aucun commentaire:

Enregistrer un commentaire