设计模式之模板方法模式

Java72

在我们的实际开发中,如果一个方法非常复杂,如果我们把所有的逻辑都写在一个方法中,维护起来非常困难,当我们想要替换它们的时候,我们必须重写一些步骤,所以代码的可扩展性很差。当你遇到这种情况时,你应该考虑今天的主角-模板方法模式。

[En]

In our actual development, if a method is extremely complex, if we write all the logic in one method, it is very difficult to maintain, and we have to rewrite some steps when we want to replace them, so the expansibility of the code is very poor. when you encounter this situation, you should consider today's protagonist-template method pattern.

一、概念理解

模板方法模式的概念非常简单。在方法中定义算法的骨架,并将某些步骤延迟到子类。模板方法使子类能够在不改变算法结构的情况下重新定义算法中的某些步骤。

[En]

The concept of the template method pattern is very simple. The skeleton of an algorithm is defined in a method, and some steps are delayed to the subclass. The template method enables the subclass to redefine some steps in the algorithm without changing the structure of the algorithm.

既然概念叫"骨架",那想当然的就是定义一个抽象类,这是模板方法模式的第一个角色——抽象模板角色,要有延迟子类实现骨架方法,这是模板方法的第二个角色——具体模板角色。

抽象模板角色:为子类定义一个或多个抽象操作来实现。这些抽象操作称为基本操作,它们是定义和实现模板方法的顶级逻辑的组成步骤。

[En]

Abstract template role: one or more abstract operations are defined for subclasses to implement. These abstract operations are called basic operations, and they are the constituent steps of a top-level logic that defines and implements a template method.

具体模板角色:实现父类定义的一个或多个抽象方法,这些抽象方法是顶级逻辑的组成步骤。每个抽象模板角色可以具有与其相对应的任意数量的特定模板角色。

[En]

Concrete template roles: implement one or more abstract methods defined by the parent class, which are the constituent steps of a top-level logic. Each abstract template role can have any number of specific template roles corresponding to it.

二、案例实现

在我们的业务开发中,我们经常需要很多对象,很多方法,而且大多数对象都有依赖关系,所以我们手动创建和管理对象是极其困难的。

[En]

In our business development, we often need a lot of objects, many methods, and most of the objects have dependencies, so it is extremely difficult for us to create and manage objects manually.

如果我们使用工厂模式用于创建对象,使用一个容器用于管理对象,那么再使用起来就变得极其简单了。

在"这个过程"中创建对象就是一个很复杂的 算法,而且创建对象的方式往往也不是单一的,我们要考虑能替换算法,这时候就可以使用模板方法模式。

输入验证码查看隐藏内容

扫描二维码关注本站微信公众号 Johngo学长
或者在微信里搜索 Johngo学长
回复 svip 获取验证码
wechat Johngo学长