Getting Started with Design Patterns: Template Method Pattern

Original address: http://te-amo.site/user/article/info/ARTICLE20180416010939282

The template method pattern is to define the skeleton of an algorithm, and delay the implementation of the specific algorithm to the subclass

Scenario: There is a function to create resources in the system, which is divided into four steps: create resources, upload to FTP server, save to database, and clear local cache. You can create image type resources and text type resources. Think about it this way. In fact, the creation process is different, and uploading, saving, and cleaning are all processed by the same algorithm, so you can use the template method mode.

structure

  • Abstract class: implements template methods and defines the skeleton of the algorithm. (ResourceTemplate)
  • Concrete classes: implement abstract methods in abstract classes, and implement complete algorithms. (ImgResource, TextResource)

design

write picture description here

accomplish

Code address:https://github.com/telundusiji/designpattern

Template for resource creation

@Slf4j
@Data
public abstract class ResourceTemplate {

    private String type;

    protected abstract void create();

    private final void uploadToFTP(){
        String serverHost = null;
        if("text".equals(type)){
            serverHost = "text.ftp.xxxx.com";
        }else if("img".equals(type)){
            serverHost = "img.ftp.xxxx.com";
        }else {
            throw new RuntimeException();
        }
        log.info("上传到FTP服务器({})成功!",serverHost);
    }

    private final void saveToDB(){
        log.info("保存到数据库成功!");
    }

    private final void clean(){
        log.info("清理本地缓存成功!");
    }

    public final void execute(){
        create();
        uploadToFTP();
        saveToDB();
        clean();
    }
}

Image type resource creation

@Slf4j
public class ImgResource extends ResourceTemplate {
    @Override
    public void create() {
        setType();
        log.info("创建text资源!");
    }

    public void setType(){
        super.setType("img");
    }
}

Text type resource creation

@Slf4j
public class TextResource extends ResourceTemplate {
    @Override
    public void create() {
        setType();
        log.info("创建text资源!");
    }

    public void setType(){
        super.setType("text");
    }

}

Advantages and disadvantages

advantage:

  • Moving unchanged behaviors to superclasses and changing behaviors are extended by subclasses, which is helpful for algorithm expansion.

shortcoming:

  • Each different implementation needs to define a subclass. When the number of subclasses is large, if the skeleton of the superclass needs to be changed, the subclasses need to be modified.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324606936&siteId=291194637