Simple Factory Pattern
1. Definition
Provides a function to create an instance of an object without caring about its specific implementation. The type of the instance being created can be an interface, an abstract class, or a concrete class.
2. Sample code
/* Interface definition, this interface can be created by a simple factory */ public interface Api{ public void operation(String s); } /*Interface concrete implementation class A*/ public class ImplA implements Api{ public void operation(String s){ System.out.println("ImplA s==" + s); } } /*Interface concrete implementation class B*/ public class ImplB implements Api{ public void operation(String s){ System.out.println("ImplB s==" + s); } }
/*Engineering factory class*/ public class Factory{ public static api createApi(int condition){ Api api = null; if(condition == 1){ api = new ImplA(); }else if(condition == 2){ api = new ImplB(); } return api; } }
/* Client call */ public class Client{ public static void main(String args[]){ Api api = Factory.createApi(1); api.operation("Simple factory is being used"); } }
3. Practical application
Although in theory, a simple factory can create anything, the scope of objects that can be created by a simple factory usually does not need to be too large. It is recommended to control it at an independent component level, or a module level, that is, a component or module is simple factory. Otherwise, the responsibilities of this simple factory class will be unclear, and there will be a hodgepodge of feelings.
The essence of the simple factory pattern: choosing an implementation