• 模板方法模式


    模板方法模式概述

    将重复的,可复用的代码抽离出来,降低代码的重复率。

    UML

    一个简单的示例:在学校的人员分为老师和学生,老师和学生每天做的相同的事情有早读,吃中饭,吃晚饭,而做不同的事情则在休息时间和去不同的宿舍楼休息。

    模板类:

    package com.template;
    
    public abstract class HighSchoolCrew {
        /**
    	 * 日常作息
    	 */
    	public final void dailyRoutine() {
    		System.out.println("早读");
    		this.doDifferentLesson();
    		System.out.println("吃午餐");
    		this.doRestTime();
    		System.out.println("吃晚饭");
    		this.doBackDormitory();
    	}
    
    	public abstract void doDifferentLesson();
    
    	public abstract void doRestTime();
    
    	public abstract void doBackDormitory();
    }
    

    学生类:

    package com.template;
    
    public class Student extends HighSchoolCrew{
    
    	@Override
    	public void doDifferentLesson() {
    		System.out.println("上语文课");
    	}
    
    	@Override
    	public void doRestTime() {
    		System.out.println("打打游戏消遣一下");
    	}
    
    	@Override
    	public void doBackDormitory() {
    		System.out.println("回柳园宿舍楼");
    	}
    
    }
    

    老师类:

    package com.template;
    
    public class Teacher extends HighSchoolCrew {
    
    	@Override
    	public void doDifferentLesson() {
    		System.out.println("给学生上语文课");
    	}
    
    	@Override
    	public void doRestTime() {
    		System.out.println("一边和老师唠嗑一边备课");
    	}
    
    	@Override
    	public void doBackDormitory() {
    		System.out.println("回教师宿舍楼");
    	}
    
    }
    

    测试类:

    package com.template;
    
    public class TestMain {
    	public static void main(String[] args) {
    		HighSchoolCrew student = new Student();
    		HighSchoolCrew teacher = new Teacher();
    		System.out.println("学生的日常作息:");
    		student.dailyRoutine();
    		System.out.println("教师的日常作息:");
    		teacher.dailyRoutine();
    	}
    }
    

    总结

    在日常的编码中,经常会遇到整体相同的业务逻辑或者业务流程,在这时候很可能就会写出重复的代码,我们可以将它相同的部分提取出来作为一个公用的方法,减少重复的代码,而不必每次都再写上一遍。但是模板方法模式由于要在父类中实现公用逻辑,需要用到抽象类来继承,每个实现需要再增加一个子类,增加了系统的复杂性。

    才疏学浅,如文中有错误,感谢大家指出。

  • 相关阅读:
    install ros-indigo-tf2
    install ros-indigo-tf
    install diagnostic_updater
    install ros-indigo-ecl-build
    "CMAKE_CXX_COMPILER-NOTFOUND"
    shell 交互式选择(select)
    install ros indigo tf2
    a标签 在新页面打开
    bootstrap.min.css.map HTTP/1.1" 404 1699
    E: Sub-process /usr/bin/dpkg returned an error code (1)
  • 原文地址:https://www.cnblogs.com/runningRookie/p/11108769.html
Copyright © 2020-2023  润新知