• 【设计模式】22、模板模式


     1 package com.shejimoshi.behavioral.TemplateMethod;
     2 
     3 
     4 /**
     5  * 功能:抽象模板类
     6  * 时间:2016年3月10日下午9:02:32
     7  * 作者:cutter_point
     8  */
     9 public abstract class AbstractTemplate
    10 {
    11     public abstract void operator1();
    12     
    13     public abstract void operator2();
    14     
    15     public void templateMethod()
    16     {
    17         operator1();
    18         operator2();
    19         System.out.println("流程操作结束");
    20     }
    21 }
     1 package com.shejimoshi.behavioral.TemplateMethod;
     2 
     3 
     4 /**
     5  * 功能:具体实现调用末班
     6  * 时间:2016年3月10日下午9:04:44
     7  * 作者:cutter_point
     8  */
     9 public class GetUp extends AbstractTemplate
    10 {
    11 
    12     @Override
    13     public void operator1()
    14     {
    15         System.out.println("闹钟响了");
    16     }
    17 
    18     @Override
    19     public void operator2()
    20     {
    21         System.out.println("穿衣服,准备起床");
    22     }
    23 
    24 }
     1 package com.shejimoshi.behavioral.TemplateMethod;
     2 
     3 
     4 /**
     5  * 功能:具体实现相应的操作2
     6  * 时间:2016年3月10日下午9:06:27
     7  * 作者:cutter_point
     8  */
     9 public class GoToBed extends AbstractTemplate
    10 {
    11 
    12     @Override
    13     public void operator1()
    14     {
    15         System.out.println("脱衣服,准备上床");
    16     }
    17 
    18     @Override
    19     public void operator2()
    20     {
    21         System.out.println("上床盖好被子,准备睡觉");
    22     }
    23 
    24 }
     1 package com.shejimoshi.behavioral.TemplateMethod;
     2 
     3 
     4 /**
     5  * 功能:定义一个操作中的算法的骨架,而将一些步骤延迟到子类。TemplateMethod使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤
     6  * 适用:一次性实现一个算法的不变部分,并将可变的行为留给子类来实现
     7  *         各子类中的公共的行为应被提取出来并集中到一个公共父类中以避免代码重复
     8  *         控制子类的扩展。模板方法只在特定点调用“hook”操作,这样就只允许在这些点进行扩展
     9  * 时间:2016年3月10日下午8:46:51
    10  * 作者:cutter_point
    11  */
    12 public class Test
    13 {
    14     public static void main(String[] args)
    15     {
    16         AbstractTemplate at;
    17         
    18         at = new GetUp();
    19         at.templateMethod();
    20         
    21         System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
    22         
    23         at = new GoToBed();
    24         at.templateMethod();
    25     }
    26 }

    测试结果:

    闹钟响了
    穿衣服,准备起床
    流程操作结束
    $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
    脱衣服,准备上床
    上床盖好被子,准备睡觉
    流程操作结束
    

      

  • 相关阅读:
    匿名对象
    JAVA中的方法重载 (参数个数不同,顺序不同,类型不同)
    构造方法的返回值和void 的区别
    一些小算法技巧
    Java基础总结(一)
    Struts2 Intercepter 笔记
    js Dom 编程
    The Bug and Exception of Hibernate
    包--R In Action
    --三种方法查询人所在部门平均工资
  • 原文地址:https://www.cnblogs.com/cutter-point/p/5263492.html
Copyright © 2020-2023  润新知