Java设计模式之模板方法模式

TEMPLATE METHOD (Class Behavioral) 
Purpose 
Identifies the framework of an algorithm, allowing implementing 
classes to define the actual behavior. 
Use When 
1 A single abstract implementation of an algorithm is needed. 
2 Common behavior among subclasses should be localized to a 
  common class. 
3 Parent classes should be able to uniformly invoke behavior in 
   their subclasses. 
4 Most or all subclasses need to implement the behavior. 
Example 
A parent class, InstantMessage, will likely have all the methods 
required to handle sending a message. However, the actual 
serialization of the data to send may vary depending on the 
implementation. A video message and a plain text message 
will require different algorithms in order to serialize the data 
correctly. Subclasses of InstantMessage can provide their 
own implementation of the serialization method, allowing the 
parent class to work with them without understanding their 
implementation details. 

Java代码 
  1. package javaPattern.templateMethod;  
  2.   
  3.   
  4. abstract class AbstractClass{  
  5.     public void templateMethod(){  
  6.         subMethod1();  
  7.         subMethod2();  
  8.     }  
  9.     public abstract void subMethod1();  
  10.     public abstract void subMethod2();  
  11. }  
  12. class ConcreteClassA extends AbstractClass{  
  13.   
  14.     @Override  
  15.     public void subMethod1() {  
  16.         System.out.println("具体类A的方法1");  
  17.           
  18.     }  
  19.   
  20.     @Override  
  21.     public void subMethod2() {  
  22.         System.out.println("具体类A的方法2");  
  23.           
  24.     }  
  25.       
  26. }  
  27. class ConcreteClassB extends AbstractClass{  
  28.   
  29.     @Override  
  30.     public void subMethod1() {  
  31.         System.out.println("具体类B的方法1");  
  32.           
  33.     }  
  34.   
  35.     @Override  
  36.     public void subMethod2() {  
  37.         System.out.println("具体类B的方法2");  
  38.           
  39.     }  
  40.       
  41. }  
  42. public class TemplateMethod {  
  43.   
  44.     public static void main(String[] args) {  
  45.         AbstractClass ac ;  
  46.         ac = new ConcreteClassA();  
  47.         ac.templateMethod();  
  48.         ac = new ConcreteClassB();  
  49.         ac.templateMethod();  
  50.     }  
  51. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值