Factory mode: Factory mode is a design pattern that uses factory-class factory methods to create objects, which are designed to create objects, but many times we will consider many other factors, such as qualifying the input, qualifying the return value for some, such as making some judgments during the creation process, These things can be separated by different factory models.
Packagecom.dhh.test;Importorg.junit.Test; Public classTest2 {@Test Public voidT ()throwsinstantiationexception, illegalaccessexception, classnotfoundexception{//Class A implements the C interface to returnA a= (a) Factory.builder ("a"); System.out.println (A.name); //B also implements a C interface that can be returned, but I tried to limit the type of the created class if B removes the C interface and cannot be returnedb b= (b) Factory.builder ("B")); System.out.println (B.name); }}classfactory{//C can actually be a return value as an interface Static PublicC Builder (String typeName)throwsinstantiationexception, illegalaccessexception, classnotfoundexception{//Reflection Creation Class//Direct Pass in a, B type name, factory internal splicing permission naming can restrict the creation of the class packageObject o=class.forname ("Com.dhh.test.") +typeName). newinstance (); //can actually be strong to C interface return(C) o; }}Interfacec{}classAImplementsc{String name= "168";}classBImplementsc{String name= "178";}
The above is the process of creating a static factory class, and all procedures for creating a class are hidden
Factory mode (think in Java design mode)