Design Patterns---Simple Factory Pattern

1 Introduction

Have you ever encountered this situation in your work, you need to instantiate different classes according to a certain condition, the basic functions of the instantiated classes are the same, and they all inherit from the same parent class. This situation is where the typical simple factory pattern is applied. Simple factory pattern, create a factory, and use the factory to create instances of other objects. Instances that are created usually have the same parent class.

2 Examples of business

Here is an example that I encountered in real work. The business requirement is to review the user comments and merchant comments (a reply to a user comment) of each order in the company's online mall, because the two comment models have some differences in attributes, and a user comment corresponds to one entity (UserComment) a piece of data Table (user_comment), the merchant responds to a comment corresponding to an entity (MerchantComment) and a data table (merchant_comment). Two entities, two data tables, corresponding to two mappers (Mybatis Plus for persistence layer framework). Now the front-end calls the interface to review the reviews and returns the review results. In the review results, there is a parameter (identity) that identifies whether to review user reviews or review merchant reviews. According to the value of identity, different mappers are called at the service layer to store the data persistently. .

3 Simple code implementation

3.1 Common attributes of UserComment and MerchantComment

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-09-01 16:28
 **/
@Data
public class CommonComment {

    private Integer id;

    private String commentContent;

    private String commentResult;
}

3.2 UserComment

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-09-01 16:29
 **/
@Data
public class UserComment extends CommonComment{

    private String userName;
}

3.3 merchantComment

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-09-01 16:29
 **/
@Data
public class MerchantComment extends CommonComment{

    private String merchantName;
}

While the MerchantComment and UserComment fields here are actually no different, this code is just a simple abstraction and far from an actual business property.

3.4 Define mapper interface

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-09-01 16:24
 **/
public interface Mapper<T> {

    /**
     * 存储实体到数据库
     * @param entity 存储的实体
     */
    void saveEntity(T entity);
}

3.5 The mapper that stores the review results of merchant reviews

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-09-01 16:26
 **/
public class MerchantCommentMapper implements Mapper<MerchantComment>{

    @Override
    public void saveEntity(MerchantComment merchantComment) {
        System.out.println("存储的是审核商户回复内容," + merchantComment.getMerchantName());
    }
}

3.6 Mapper for storing user comment review results

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-09-01 16:26
 **/
public class UserCommentMapper implements Mapper<UserComment>{

    @Override
    public void saveEntity(UserComment userComment) {
        System.out.println("存储的是审核用户评论内容," + userComment.getUserName());
    }

3.7 Simple Factory SimpleFactory

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-09-01 16:38
 **/
public class SimpleFactory {

    public static Mapper createMapper(String identity){
        Mapper mapper = null;
        switch (identity){
            case "merchant":
                mapper = new MerchantCommentMapper();
                break;
            case  "user":
                mapper = new UserCommentMapper();
                break;
            default:
        }
        return mapper;
    }

    public static CommonComment createCommentEntity(String identity, CommonComment commonComment){
       CommonComment comment = null;
        switch (identity){
            case "merchant":
                MerchantComment merchantComment = new MerchantComment();
                merchantComment.setId(commonComment.getId());
                merchantComment.setCommentContent(commonComment.getCommentContent());
                merchantComment.setCommentResult(commonComment.getCommentResult());
                merchantComment.setMerchantName("hello,我是商户评论回复");
                comment = merchantComment;
                break;
            case  "user":
                UserComment userComment = new UserComment();
                userComment.setId(commonComment.getId());
                userComment.setCommentContent(commonComment.getCommentContent());
                userComment.setCommentResult(commonComment.getCommentResult());
                userComment.setUserName("hello,我是用户评论");
                comment = userComment;
                break;
            default:
        }
        return comment;
    }
}

A simple factory is equivalent to having two production lines, one for mapper and one for comment. The production line for producing comments can be simpler, and there is no packaging here.

3.8 Main class

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-09-01 16:23
 **/
public class MainClass {
    public static void main(String[] args) {

        boolean flag = true;
        while (flag) {
            //模拟接口参数
            Scanner sc = new Scanner(System.in);
            String identity = sc.nextLine();
            if (identity.equals("exit")){
                flag = false;
            }else {

                //模拟接口接待的审核结果body
                CommonComment comment = new CommonComment();
                comment.setId(1);
                comment.setCommentContent("审核内容");
                comment.setCommentResult("yes");

                Mapper mapper = SimpleFactory.createMapper(identity);
                if (mapper == null) {
                    System.out.println("身份标识参数输入错误");
                    continue;
                }
                mapper.saveEntity(SimpleFactory.createCommentEntity(identity, comment));
            }
        }

    }
}

3.9 Running Results

4 UML class diagram

UML class diagrams are automatically generated with the help of tools from idea.

4.1 mapper class diagram

 4.2 Comment class diagram

 

5 citations

1. "Dahua Design Patterns" 

2. Java implementation example of simple factory pattern

6 Source address

https://github.com/airhonor/design-pattern-learning/tree/main/src/com/hz/design/pattern/simple/factory

 

Guess you like

Origin blog.csdn.net/honor_zhang/article/details/120042198