The real advantage of Factory Pattern

I have been using factory template since year. I once feel that the real advantage would be just plain 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 the above code, I feel like the factory template is just decorating the code, please let me know if my understanding is wrong.

+4
source share
3 answers

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

In addition, your example is extremely simple. In other cases, input can be more complex than a string that exactly matches the type. The input may be a file with a specific format, which requires, for example, reading a specific version.

+2
source

Instead of decorating, consider the following example

let's say that you are doing a test class, and your partner implements B, C, D .... (others you don’t know) .. how can you handle this?

Factory template will help you copy one part of your application without requiring to know other parts.

+1
source

I think the DP book has an Intent section, which is even more important than the structure of the template itself. Your sample is quite trivial. In more complex cases, Factory helps you encapsulate creation details. Taking your sample. Imagine that "new B ()" and "new C ()" are scattered across your code. Then you need to change B to say SuperB , and you have to change it in every place of the code. In Factory, you change it in only one place.

0
source

Source: https://habr.com/ru/post/1483158/


All Articles