samedi 9 janvier 2021

Trying to figure out Factory Pattern in a Java - Spring application

I’m trying to build a sort of workflow functionality in my Spring application. This is what the i’m trying to achieve -

Request object from UI will have workflowType and action variables. workflowType in the request will help determining what service impl to call and action value would tell what business functionality to be performed.

Currently there is only one workflow type and in the future there will be additional types. For example -

  • A workflow with type WorkflowOne will have actions like Pending, Approve etc.
  • A workflow with type WorkflowTwo will have totally different actions like Hold, Processing etc.

Here is what I’m planning to do:

A WorkflowService interface with default methods for all the methods different impls will need.

interface WorkflowService {
    default void pending() {}
    default void approve() {}
    default void hold() {}
    default void processing() {}

}

WorkflowOne impl which has action items Pending and Approve

class WorkFlowOne implements WorkflowService{

public void pending(){
 // do pending
}

public void approve(){
 // do approve
}

}

WorkflowTwo impl which has action items hold and processing

class WorkFlowTwo implements WorkflowService{

public void hold(){
 // do hold
}

public void processing(){
 // do hold
}

Now, in a xml, create a util:map with workflowType(same as workflowType value coming from the request from UI) and WorkflowService Impls. Inject the map to the controller to get the right Workflow Impl.

class WorkflowController{

@Resource(name = "workflowServiceFactory")
Private Map<String, WorkflowService> workflowServiceFactory

public void manageWorkflow(@RequestParam WorkflowRequest workflowRequest) {
       WorkflowService workflowService= workflowServiceFactory.get(workflowRequest.getWorkflowType());

    }
}

Now, I have the correct WorkflowService Impl available. Is there a way I can call method from impl using the action value from WorkflowRequest? For example, if workflowRequest.getAction() = “PENDING”, call workflowService.pending()

Aucun commentaire:

Enregistrer un commentaire