Devsined
Devsined

Reputation: 3521

Design pattern for a implementation of multiple strategies based on different inputs

There is a design pattern that I can apply to this kind of scenario?

I have processes classes that implements BaseProcess class: BaseProcess has a CreateProcess(BaseObject o) method and BaseObject has two childs or many.

 ProcessClassA : BaseProcess
 ProcessClassB : BaseProcess

 ObjectA : BaseObject 
 ObjectB : BaseObject 

I want to be able to have a class Process that can have multiples ProcessClasses like in this case 2 classes but that can have more in the future like 3 classes or more and that process. And I want to use the class like this:

Process.Process(BaseObject o) and send specific object and let the Process class call the specific class such as ProcessClassA if I send ObjectA. The problems is I dont want to use if inside process becuse I will need to one that class when I add ProcessClassC

Example:

ObjectA exampleObj = new ObjectA  

Process p = new Process(List<BaseProcess>{ProcessClassA ,ProcessClassB }) //Something like this but dont need to be in the contructor or be a list could be //something else but that allows not to violate Open Close principle.

p.Process(exampleObj) => ProcessClassA.Process(exampleObj)  

Upvotes: 0

Views: 1406

Answers (1)

&#214;mer Erden
&#214;mer Erden

Reputation: 8793

How about mapping if you don't want to use if clause in your Process Manager Class ?

like this ;

HashMap<Class, BaseProcess> processMap = new HashMap<Class, BaseProcess>();

processMap.put(ObjectA.class, new ProcessClassA());
processMap.put(ObjectB.class, new ProcessClassB());
//... so on

Process p = new Process(processMap);
p.process(new ObjectA());

process method and constructor should be like this which in your Process Manager Class

private HashMap<Class, BaseProcess> processMap;

public Process(HashMap<Class, BaseProcess> processMap)
{
   this.processMap = processMap;
}

public void process(BaseObject objectInstance)
{
   //"which returns ProcessClass?:BaseClass"
   processMap.get(objectInstance.getClass()).process(objectInstance);
}

I am assuming that your ProcessClassA or B (BaseProcess) is a stateless. If not and if you want to create ProcessClassA for per ObjectA's instance then you need to change your hashmap like this HashMap<Class, Class> so you can bind ObjectA.class to ProcessA.class. and create instance of ProcessA class in Process Class constructor.

Also i am sure there will be better way to naming those classes try to use Abstract classes and Generic Types.

Upvotes: 1

Related Questions