Leggy
Leggy

Reputation: 155

Avoid multiple if-else statements in a factory class [language agnostic]

I have some data that I'm trying to sift through and I can't figure out a smart way of doing this. Let's say I have 3 types:

A, B, C and they all extend a class S.

If I create a factory that just creates and returns and object of type S, it seems like it would be very procedural. The factory's implementation in pseudo-code would be something like this:

class Factory {
    func create_obj(input_data) -> S {
        if type(input_data) is A {
            return A()
        }
        else if type(input_data) is B {
            return B()
        }
        else {
            return C()
        }
    }
}

Now, I have a lot of different data types that it could possibly be. That means this algorithm in the worst case is in quadratic time. Is there a better solution, design pattern, or any optimizations I can look at? To be more specific, I'm creating instances of certain data types and the input is lines of text.

Upvotes: 1

Views: 248

Answers (1)

Chetan Kinger
Chetan Kinger

Reputation: 15212

One way to approach the problem would be to use a pre-populated associative array where the key is a string representing a line/value in the file and the value is the object that should be returned for that line.

Sample implementation :

Let file be an asscociateive array. On startup, the factory should pre-populate this array with string to object mappings :

files["A"] = new A();
files["B"] = new B();
files["C"] = new C();

The factory can then be passed a string which it will lookup in the associative array to fetch the corresponding pre-populated object :

func create_obj(input_data) -> S {
   return files[input_data];
}

Upvotes: 4

Related Questions