Definition: The simple factory pattern is the creation pattern, also known as the factory method pattern, in which a factory object decides which instance of a product pattern to create.

Simple Factory Pattern class diagram:

In simple Factory mode there are the following roles:

  • Factory: The Factory class, which is at the heart of the simple Factory pattern and is responsible for implementing the logic inside the creation instance.
  • IProduct: Abstract product class, which is the parent of all objects created by the simple factory pattern and is responsible for describing the common interfaces that all instances work on.
  • Product: Concrete Product class, which is the goal of the simple factory class.
The DEMO & code

Scenario: The company has recently connected to two biopsies SDKS, and more will be connected in the future. The code is as follows:

Public abstract class AbstractLivingDetection {/** * public abstract void startDetection(); }Copy the code
public class HaiXinLivingDetection extends AbstractLivingDetection {
    @Override
    public void startDetection() {
        System.out.println("Start haixin in vivo test."); }}Copy the code
public class TongFuDunLivingDetection extends AbstractLivingDetection {
    @Override
    public void startDetection() {
        System.out.println("Activate the shield biopsy."); }}Copy the code
public class LivingDetectionFactory {
    public static AbstractLivingDetection createLivingDetection(String type){
        AbstractLivingDetection livingDetection = null;
        switch (type) {case "tongfudun":
                livingDetection = new TongFuDunLivingDetection();
                break;
            case "haixin":
                livingDetection = new HaiXinLivingDetection();
                break;
            default:
                break;
        }
        returnlivingDetection; }}Copy the code
Usage scenarios
  • The factory class is responsible for creating fewer objects.
  • The customer only needs to know the parameters passed into the factory class and does not need to care about the logic of creating the object.
Advantages:
  • The user can obtain the corresponding class instance according to the parameter, avoiding directly instantiating the class and reducing the coupling.
Disadvantages:
  • The instantiable types are determined at compile time. If you add a new type, you need to modify the factory, which violates the open and closed principle. A simple factory needs to know all the types to be generated and is not suitable when there are too many subclasses or too many subclass hierarchies.

Code has been uploaded to Github