Factory approach (Factory method)
* Factory method puts different products in different factory classes that implement the Factory interface (Factoryaimpl,factorybimpl ... Inside
* So even if one of the factory class is out of the question, other factory classes will work and not be affected by each other.
* After adding new products, you only need to add a factory interface factory class, can be achieved without modifying the existing code
Code Explanation:
1. Create product interface products and create 2 product sub-categories Android phones, Apple phones, all implement the Product interface
Public Interface Product { }
Product {public Android () { System.out.println ("Production of an Android phone ...");} }
Product {public apple () { System.out.println ("Producing an Apple phone ...");} }
2. Create a factory interface, add a production method (return value is product), and create a corresponding factory implementation class for each product
Public Interface Factory { /** * produces a product @return*/ Public Product process ();}
public class androidfactory implements Factory {@Override Span style= "color: #0000ff;" >public Product process () { return new Android (); }}
Public class Implements Factory { @Override public Product process () { Returnnew Apple ();} }
3. Client invocation: Test
Public Static void Main (string[] args) {// Factory Factory = new Applefactory (); // Apple Factory New androidfactory (); // Android Factory factory.process (); }
In this way, only the new Xxxfactory () can be modified to produce the corresponding product of the plant.
Defects
* Factory method for each type of product (such as mobile phone class, car class ...) ) Each implementation class (such as the mobile phone class [Android factory, Apple Factory] car class [BMW factory, Mercedes-Benz Factory]) to create a corresponding factory class, when there are hundreds of or even thousands of products, also must have the corresponding hundreds of thousands of factory class, which there is a legend of the class explosion , For future maintenance, it is simply a disaster .....
Factory Method Factory Factory mode FactoryMethod