文章目录
- 一、模板方法模式定义
- 二、例子
- 2.1 菜鸟教程例子
- 2.1.1 抽象类Game 定义了play方法的执行步骤。
- 2.1.2 继承Game类并实现initialize、startPlay、endPlay方法。
- 2.1.3 使用
- 2.2 JDK源码 —— Map
- 2.3 Spring源码 —— JdbcTemplate
- 2.4 Spring源码 —— RestTemplate
- 三、其他设计模式
一、模板方法模式定义
类型: 行为型模式
定义了方法的实现步骤(可以有默认的具体实现),并提供1~n个可扩展/重写的方法,实现特定步骤的算法可替换。
二、例子
2.1 菜鸟教程例子
2.1.1 抽象类Game 定义了play方法的执行步骤。
public abstract class Game {abstract void initialize();abstract void startPlay();abstract void endPlay();//模板public final void play(){//初始化游戏initialize();//开始游戏startPlay();//结束游戏endPlay();}
}
2.1.2 继承Game类并实现initialize、startPlay、endPlay方法。
public class Cricket extends Game {@Overridevoid endPlay() {System.out.println("Cricket Game Finished!");}@Overridevoid initialize() {System.out.println("Cricket Game Initialized! Start playing.");}@Overridevoid startPlay() {System.out.println("Cricket Game Started. Enjoy the game!");}
}
public class Football extends Game {@Overridevoid endPlay() {System.out.println("Football Game Finished!");}@Overridevoid initialize() {System.out.println("Football Game Initialized! Start playing.");}@Overridevoid startPlay() {System.out.println("Football Game Started. Enjoy the game!");}
}
2.1.3 使用
public class TemplatePatternDemo {public static void main(String[] args) {Game game = new Cricket();game.play();System.out.println();game = new Football();game.play(); }
}
2.2 JDK源码 —— Map
public interface Map<K, V> {V get(Object key);V put(K key, V value);V remove(Object key);default V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {Objects.requireNonNull(remappingFunction);Objects.requireNonNull(value);V oldValue = get(key);V newValue = (oldValue == null) ? value : remappingFunction.apply(oldValue, value);if (newValue == null) {remove(key);} else {put(key, newValue);}return newValue;}}
2.3 Spring源码 —— JdbcTemplate
JdbcTemplate 也是运用了模板模式。
不过具体实现并非通过重写方法实现,而是通过参数传进来的RowMapper。
public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {public <T> T queryForObject(String sql, RowMapper<T> rowMapper) throws DataAccessException {List<T> results = this.query(sql, rowMapper);return DataAccessUtils.nullableSingleResult(results);}
}
换个角度来看,这是不是也是一种策略模式?
2.4 Spring源码 —— RestTemplate
RestTemplate 也是运用了模板模式。
具体实现也并非通过重写方法实现,而是通过参数传RequestCallback 、ResponseExtractor。
public class RestTemplate extends InterceptingHttpAccessor implements RestOperations {@Nullableprotected <T> T doExecute(URI url, @Nullable HttpMethod method, @Nullable RequestCallback requestCallback, @Nullable ResponseExtractor<T> responseExtractor) throws RestClientException {Assert.notNull(url, "URI is required");Assert.notNull(method, "HttpMethod is required");ClientHttpResponse response = null;Object var14;try {ClientHttpRequest request = this.createRequest(url, method);if (requestCallback != null) {requestCallback.doWithRequest(request);}response = request.execute();this.handleResponse(url, method, response);var14 = responseExtractor != null ? responseExtractor.extractData(response) : null;} catch (IOException var12) {String resource = url.toString();String query = url.getRawQuery();resource = query != null ? resource.substring(0, resource.indexOf(63)) : resource;throw new ResourceAccessException("I/O error on " + method.name() + " request for \"" + resource + "\": " + var12.getMessage(), var12);} finally {if (response != null) {response.close();}}return var14;}
}
三、其他设计模式
创建型模式
结构型模式
- 1、设计模式——装饰器模式(Decorator Pattern)+ Spring相关源码
行为型模式
- 1、设计模式——访问者模式(Visitor Pattern)+ Spring相关源码
- 2、设计模式——中介者模式(Mediator Pattern)+ JDK相关源码
- 3、设计模式——策略模式(Strategy Pattern)+ Spring相关源码
- 4、设计模式——状态模式(State Pattern)
- 5、设计模式——观察者模式(Observer Pattern)+ Spring相关源码