Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Real advantage of Factory Pattern [closed]

I have been using factory pattern since a year now. Sometime I only feel that the real advantage would just be clean code. Let me explain,

interface A {

    public void test();
}

class B implements A {
    public void test() {

    }
}

class C implements A {
    public void test() {

    }
}

class Factory {
    public static A getObject(String name){
        if(name.equalsIgnoreCase("B")){
            return new B();
        }else if(name.equalsIgnoreCase("C")){
          return new C();
        }
        return new B(); 

    }
}

public class Test {

    public static void main(String[] args) {
        A a = Factory.getObject(args[0]);

        // if i dint use factory pattern
        A nofactory=null;
        if(args[0].equalsIgnoreCase("B")){
            nofactory= new B();
        }else if(args[0].equalsIgnoreCase("C")){
            nofactory= new C();
        }
    }
}

From above code I feel factory pattern just beautifies the code, please let me know if my understanding is wrong.

like image 391
Ashwin Avatar asked Oct 21 '22 09:10

Ashwin


1 Answers

If interface A and classes B and C are in a library and your code is the main method that uses the library, that means that classes D, E etc can be added to the library and you can use them without changing your code. The responsibility of choosing which implementation to use is moved to the library.

Also, your example is extremely simple. Other times the input may be more complex than a string that exactly matches the type. The input could be a file with a specific format that needs a certain implementation to be read for instance.

like image 153
Ludwig Magnusson Avatar answered Oct 29 '22 14:10

Ludwig Magnusson