Java 8实战 第二章笔记

行为参数化,一个处理频繁改变需求的软件开发模式。原则:在编写类似代码之后,尝试将其抽象化。

方法1:为方法增加参数。

方法2:定义一族算法,把它们封装起来(称为"策略"),然后在运行时选择一个算法。

行为参数化:让方法接受多种行为(或战略)作为参数,并在内部使用,来完成不同的行为。

Strategy patternis a behavioral software design pattern that enables selecting an algorithm at runtime. The strategy pattern

  • defines a family of algorithms,
  • encapsulates each algorithm, and
  • makes the algorithms interchangeable within that family.

根据抽象条件筛选

  • 传递代码/行为给方法
  • 多种行为,一个参数。

Java8 之前可使用匿名类来减少冗余代码。

sort方法的行为可以用java.util.Comparator对象来参数化。

你可以用Runnable接口表示一个要执行的代码块(但不会返回任何接口,即void)。

原文地址:https://www.cnblogs.com/Hu-Yan/p/8546966.html