1, Simple factory

;

Definition introduction

  1. Classification: from the type division of design patterns, simple factory pattern belongs to creation design pattern, also known as static factory method pattern, which belongs to a special case of factory pattern family, but does not belong to 23 design patterns.
  2. Definition: the simple factory pattern is an instance of a factory object creating a concrete abstract product.
  3. Class diagram:

code analysis

1. Abstract products

public interface IComputer {
    void create();
}

2. Specific products

  • Product category 1
public class AsusCom implements IComputer{

    @Override
    public void create() {
        System.out.println("asus is coming...");
    }
}
  • Product category 2
public class DellCom implements IComputer {
    @Override
    public void create() {
        System.out.println("dell is coming...");
    }
}
  • Product category 3
public class MackProCom implements IComputer {
    @Override
    public void create() {
        System.out.println("mack pro is coming");
    }
}

3. Factory

  • Create specific product class instance specified by factory class
public class Factory {

    public static IComputer createProduct(String str) {
        if (str == null || "".equals(str)){
            return null;
        }else if (str.equals("asus")){
            return new AsusCom();
        }else if (str.equals("dell")){
            return new DellCom();
        }else if (str.equals("pro")){
            return new MackProCom();
        }
        return null;
    }
}

4. Client call

  • The passed in string parameter specifies to create a classification for a specific product
public class Client {
    public static void main(String[] args) {
        IComputer computer = Factory.createProduct("asus");
        computer.create();

        IComputer computer1 = Factory.createProduct("pro");
        computer1.create();
    }
}

summary

Simple factory method design pattern composition
1. IComputer(interface/abstract)
2. Dell || Asus || MackPro(subClass)
3. Factory (the factory class creates a specific instance based on the parameters passed in)

Posted by miro on Tue, 12 May 2020 07:52:06 -0700