JDK中的模板设计模式,找不到定义要按顺序执行的方法集的方法 [英] Template design pattern in JDK, could not find a method defining set of methods to be executed in order

查看:11
本文介绍了JDK中的模板设计模式,找不到定义要按顺序执行的方法集的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读模板设计模式.根据我目前的理解,当我们有一个算法,其中有一组定义的过程(方法)要按顺序完成时,可以使用模板设计模式.主要参与者是

I am reading about Template design pattern. As per my current understanding, Template design pattern can be used when we have an algorithm with defined set of processes(methods) to be done in order. Main players are

1.抽象模板类提供了一个模板方法,定义了过程(方法)和执行顺序.通常这个方法是最终的,所以它的行为不会被修改.模板方法中提到的过程(方法)很少提供默认实现,其他依赖于扩展抽象模板类类型的具体类被保留为抽象.

1.Abstract Template class providing a template method defining the processes (methods) and the order of execution. Usually this method is made final, so as its behavior is not modified. Few of the processes(methods) mentioned in the template method are provided with default implementation and others depending upon the concrete classes extending the Abstract template class types are left as abstract.

2.扩展模板方法的具体类.如有必要,它们会覆盖默认方法,并提供抽象模板类中定义的抽象方法的实现.

2.Concrete classes extending the Template method. These override the default methods if necessary and provided the implementation for the abstract methods defined in the Abstract Template class.

我尝试在 JDK 中搜索它的实现,在阅读这些类实现此模式后,我查看了 java.io 类.我找不到任何定义一组进程(方法)和执行顺序的方法.

I tried searching for its implementation in JDK, i looked at java.io classes after reading that these classes implement this pattern. I was not able to find any method defining a set of processes(methods) and the order of execution.

请提供您宝贵的意见.

推荐答案

一个简单的例子是 java.io.OutputStream.

A simple example is java.io.OutputStream.

模板方法
public void write(byte b[],int off, int len).

它调用抽象方法
public abstract void write(int b),
必须由OutputStream的子类实现.

It calls the abstract method
public abstract void write(int b),
which must be implemented by a subclass of OutputStream.

在这种情况下,模板的不变部分是每个OutputStream通用的基本错误处理,而模板的变体部分是实际编写的,具体到每个具体实现.

In this case the invariant portion of the template is the basic error handling that is common to every OutputStream, while the variant portion of the template is the actual writing, which is specific to each concrete implementation.

你对模式的理解是正确的;然而,它不必那么复杂.基本上,任何在同一类中调用抽象方法的具体方法都是模板方法.

Your understanding of the pattern is correct; however, it needn't be that complex. Basically, any concrete method which calls an abstract method in the same class is a template method.

这篇关于JDK中的模板设计模式,找不到定义要按顺序执行的方法集的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆