Java – the real advantage of the factory model

I've been using the factory model for a year Sometimes I just think the real advantage is 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 the above code, I think the factory pattern is just beautifying the code. If my understanding is wrong, please tell me

Solution

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

In addition, your example is very simple At other times, the input may be more complex than a string of exactly matching types The input can be a file with a specific format, such as an implementation that needs to be read

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>