Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which design pattern to use for my use case?

I have a use case where the input is set of parameters (say A, B, C, D) and data (say XYZ). Based on the parameters(A,B,C,D) i have to process the data(XYZ) and respond back. The processing logic can be unique or common based on parameters(say do something#1 only when A, do something#2 when A and C, do something#2 when B, C and D and so on). I might also need to maintain the order of processing.

The current implementation is based on if-else loops. I am looking at chain of responsibility, pipeline design patterns. But is there any other suitable design pattern for the above task ?

Example using if-else blocks:

I/P : A={A1,A2,A3},B={B1,B2,B3},C={C1,C2,C3},D={D1,D2,D3} and XYZ="foo"

if (A == A1)
{
    //dosomething-A1

    if (B == B1)
    {
        //dosomething-B1

        if (C == C2)
        {
            //dosomething-C2
        }
    }
    else if (B == B2)
    {
        //dosomething-B2
    }

    if (C == C2)
    {
        //dosomething-C2

        if (D == D1)
        {
            //dosomething-D1
        }
        else if (D == D3)
        {
            //dosomething-D3
        }
    }
}
else if (A == A2)
{
    //dosomething-A2
    ...
}
else if (A == A3)
{
    //dosomething-A3
    ...
}
like image 749
josh Avatar asked Jan 21 '16 18:01

josh


People also ask

Which design pattern is the most appropriate?

Factory Design Pattern One of the most popular design patterns used by software developers is a factory method. It is a creational pattern that helps create an object without the user getting exposed to creational logic.

What are the design patterns you have used?

These design patterns are about organizing different classes and objects to form larger structures and provide new functionality. Structural design patterns are Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Private Class Data, and Proxy.


2 Answers

Chain seem to fit this very well, if it is reused. Another option is to use handlers stored in a map, where the key is the appropriate parameter value. This works well for limited set of possible values passed as the parameters. You'll get something like:

handlers.get( a ).handle(XYZ)

So, completely if-less on your part. But again, this does not fit all purposes.

like image 178
Michael Bar-Sinai Avatar answered Oct 05 '22 23:10

Michael Bar-Sinai


Look for something like command pattern. Based on the parameters data need to be processed. Internal implementation should not be exposed outside. So, from exposed interface perspective it has to take parameter and data and command pattern need to identify which method to execute based on parameters.

like image 45
BValluri Avatar answered Oct 05 '22 23:10

BValluri