Factory method model

  • Definition: Defines an interface to create an object, but lets the class that implements the interface decide which class to instantiate. Factory methods defer class instantiation to subclasses.
  • Type: Create type
  • Applicable scenario:

    • Creating objects requires a lot of repetitive code
    • The client (application layer) does not depend on the details of how the product class instance is created, implemented, etc.
    • A class uses its subclasses to specify which object to create
  • Advantages:

    • The user only needs to care about the factory corresponding to the desired product, not about the creation details
    • Add new products in line with the open – closed principle, improve scalability
  • Disadvantages:

    • It is easy to have too many classes and add complexity
    • It increases the abstractness and difficulty of understanding the system
Code sample

Entity class:

public abstract class Video {
    public abstract void produce();
}
Public class JavaVideo extends Video {@Override public void produce() {System.out.println();} public class JavaVideo extends Video {public void produce() {System.out.println(); }}
Public class PythonVideo extends Video {public void produce() {System.out.println(); public class PythonVideo extends Video {public void produce() {System.out.println(); }}
Public class Fevideo extends Video{@Override public void produce() {System.out.println(); }}

The factory class:

public abstract class VideoFactory {
    public abstract Video getVideo();
}
public class JavaVideoFactory extends VideoFactory{ @Override public Video getVideo() { return new JavaVideo(); }}
public class PythonVideoFactory extends VideoFactory{ @Override public Video getVideo() { return new PythonVideo(); }}
public class FEVideoFactory extends VideoFactory{ @Override public Video getVideo() { return new FEVideo(); }}

The test class:

public class Test { public static void main(String[] args) { VideoFactory javaVideoFactory = new JavaVideoFactory(); // VideoFactory pythonVideoFactory = new PythonVideoFactory(); // VideoFactory feVideoFactory = new FEVideoFactory(); Video video = javaVideoFactory.getVideo(); video.produce(); }}

XXXVideo and XXXVideoFactory are extensible, adding or removing the corresponding part will not affect the existing code implementation of other parts, or the remaining part of the code implementation.

Application scenarios

The JDK:

  • Collection (Iterator)

    • Collection – VideoFactroy
    • ArrayList – JavaVideoFactroy
    • Iterator – Video
    • Itr – JavaVideo
  • URLStreamHandlerFactory
  • Loggerfactory