'How to handle the if else structure for creating the concrete class in strategy pattern
I am new to design pattern.
My current code without strategy pattern:
def get_src_data(type):
if type == "obj1":
return fetch_src_obj1()
elif type == "obj2":
return fetch_src_obj2()
...
...
...
after applying strategy pattern, I have created a concrete class for each type of object source which implements a common interface and created a context class via which the user can access the concrete class. Now I have to pass the concrete class to the context to get the data. This Works!!
class AbsStrategy(ABC):
@abstractmethod
def get_src_data():
pass
class Context(AbsStrategy):
def __init__(strategy):
self.strategy = strategy
def process_data(strategy):
self.strategy.get_src_data()
But for creating the concrete class I am again forced to create the if else/dict mapping for creating the concrete class instance.
I found factory pattern can provide a solution over here, but couldn't find any easier example to comprehend. Hence like to have a help from the community
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
