Skip to content

Commit 350881d

Browse files
第二十五章 设计模式 翻译更新(“函数对象”小节翻译完成) (#377)
1 parent 9ad128c commit 350881d

File tree

1 file changed

+252
-0
lines changed

1 file changed

+252
-0
lines changed

docs/book/25-Patterns.md

+252
Original file line numberDiff line numberDiff line change
@@ -789,6 +789,258 @@ KungFuGuy now battles a NastyWeapon
789789

790790
## 函数对象
791791

792+
一个 *函数对象* 封装了一个函数。其特点就是将被调用函数的选择与那个函数被调用的位置进行解耦。
793+
794+
*《设计模式》* 中也提到了这个术语,但是没有使用。然而,*函数对象* 的话题却在那本书的很多模式中被反复论及。
795+
796+
### 命令模式
797+
798+
从最直观的角度来看,*命令模式* 就是一个函数对象:一个作为对象的函数。我们可以将 *函数对象* 作为参数传递给其他方法或者对象,来执行特定的操作。
799+
800+
Java 8之前,想要产生单个函数的效果,我们必须明确将方法包含在对象中,而这需要太多的仪式了。而利用Java 8的lambda特性, *命令模式* 的实现将是微不足道的。
801+
802+
```java
803+
// patterns/CommandPattern.java
804+
import java.util.*;
805+
806+
public class CommandPattern {
807+
public static void main(String[] args) {
808+
List<Runnable> macro = Arrays.asList(
809+
() -> System.out.print("Hello "),
810+
() -> System.out.print("World! "),
811+
() -> System.out.print("I'm the command pattern!")
812+
);
813+
macro.forEach(Runnable::run);
814+
}
815+
}
816+
/* Output:
817+
Hello World! I'm the command pattern!
818+
*/
819+
```
820+
821+
*命令模式* 的主要特点是允许向一个方法或者对象传递一个想要的动作。在上面的例子中,这个对象就是 **macro** ,而 *命令模式* 提供了将一系列需要一起执行的动作集进行排队的方法。在这里,*命令模式* 允许我们动态的创建新的行为,通常情况下我们需要编写新的代码才能完成这个功能,而在上面的例子中,我们可以通过解释运行一个脚本来完成这个功能(如果需要实现的东西很复杂请参考解释器模式)。
822+
823+
*《设计模式》* 认为“命令模式是回调的面向对象的替代品”。尽管如此,我认为"back"(回来)这个词是callback(回调)这一概念的基本要素。也就是说,我认为回调(callback)实际上是返回到回调的创建者所在的位置。另一方面,对于 *命令* 对象,通常只需创建它并将其交给某种方法或对象,而不是自始至终以其他方式联系命令对象。不管怎样,这就是我对它的看法。在本章的后面内容中,我将会把一组设计模式放在“回调”的标题下面。
824+
825+
### 策略模式
826+
827+
*策略模式* 看起来像是从同一个基类继承而来的一系列 *命令* 类。但是仔细查看 *命令模式*,你就会发现它也具有同样的结构:一系列分层次的 *函数对象*。不同之处在于,这些函数对象的用法和策略模式不同。就像前面的 `io/DirList.java` 那个例子,使用 *命令* 是为了解决特定问题 -- 从一个列表中选择文件。“不变的部分”是被调用的那个方法,而变化的部分被分离出来放到 *函数对象* 中。我认为 *命令模式* 在编码阶段提供了灵活性,而 *策略模式* 的灵活性在运行时才会体现出来。尽管如此,这种区别却是非常模糊的。
828+
829+
另外,*策略模式* 还可以添加一个“上下文(context)”,这个上下文(context)可以是一个代理类(surrogate class),用来控制对某个特定 *策略* 对象的选择和使用。就像 *桥接模式* 一样!下面我们来一探究竟:
830+
831+
```java
832+
// patterns/strategy/StrategyPattern.java
833+
// {java patterns.strategy.StrategyPattern}
834+
package patterns.strategy;
835+
import java.util.function.*;
836+
import java.util.*;
837+
838+
// The common strategy base type:
839+
class FindMinima {
840+
Function<List<Double>, List<Double>> algorithm;
841+
}
842+
843+
// The various strategies:
844+
class LeastSquares extends FindMinima {
845+
LeastSquares() {
846+
// Line is a sequence of points (Dummy data):
847+
algorithm = (line) -> Arrays.asList(1.1, 2.2);
848+
}
849+
}
850+
851+
class Perturbation extends FindMinima {
852+
Perturbation() {
853+
algorithm = (line) -> Arrays.asList(3.3, 4.4);
854+
}
855+
}
856+
857+
class Bisection extends FindMinima {
858+
Bisection() {
859+
algorithm = (line) -> Arrays.asList(5.5, 6.6);
860+
}
861+
}
862+
863+
// The "Context" controls the strategy:
864+
class MinimaSolver {
865+
private FindMinima strategy;
866+
MinimaSolver(FindMinima strat) {
867+
strategy = strat;
868+
}
869+
List<Double> minima(List<Double> line) {
870+
return strategy.algorithm.apply(line);
871+
}
872+
void changeAlgorithm(FindMinima newAlgorithm) {
873+
strategy = newAlgorithm;
874+
}
875+
}
876+
877+
public class StrategyPattern {
878+
public static void main(String[] args) {
879+
MinimaSolver solver =
880+
new MinimaSolver(new LeastSquares());
881+
List<Double> line = Arrays.asList(
882+
1.0, 2.0, 1.0, 2.0, -1.0,
883+
3.0, 4.0, 5.0, 4.0 );
884+
System.out.println(solver.minima(line));
885+
solver.changeAlgorithm(new Bisection());
886+
System.out.println(solver.minima(line));
887+
}
888+
}
889+
/* Output:
890+
[1.1, 2.2]
891+
[5.5, 6.6]
892+
*/
893+
```
894+
895+
`MinimaSolver` 中的 `changeAlgorithm()` 方法将一个不同的策略插入到了 `私有` 域 `strategy` 中,这使得在调用 `minima()` 方法时,可以使用新的策略。
896+
897+
我们可以通过将上下文注入到 `FindMinima` 中来简化我们的解决方法。
898+
899+
```java
900+
// patterns/strategy/StrategyPattern2.java // {java patterns.strategy.StrategyPattern2}
901+
package patterns.strategy;
902+
import java.util.function.*;
903+
import java.util.*;
904+
905+
// "Context" is now incorporated:
906+
class FindMinima2 {
907+
Function<List<Double>, List<Double>> algorithm;
908+
FindMinima2() { leastSquares(); } // default
909+
// The various strategies:
910+
void leastSquares() {
911+
algorithm = (line) -> Arrays.asList(1.1, 2.2);
912+
}
913+
void perturbation() {
914+
algorithm = (line) -> Arrays.asList(3.3, 4.4);
915+
}
916+
void bisection() {
917+
algorithm = (line) -> Arrays.asList(5.5, 6.6);
918+
}
919+
List<Double> minima(List<Double> line) {
920+
return algorithm.apply(line);
921+
}
922+
}
923+
924+
public class StrategyPattern2 {
925+
public static void main(String[] args) {
926+
FindMinima2 solver = new FindMinima2();
927+
List<Double> line = Arrays.asList(
928+
1.0, 2.0, 1.0, 2.0, -1.0,
929+
3.0, 4.0, 5.0, 4.0 );
930+
System.out.println(solver.minima(line));
931+
solver.bisection();
932+
System.out.println(solver.minima(line));
933+
}
934+
}
935+
/* Output:
936+
[1.1, 2.2]
937+
[5.5, 6.6]
938+
*/
939+
```
940+
941+
`FindMinima2` 封装了不同的算法,也包含了“上下文”(Context),所以它便可以在一个单独的类中控制算法的选择了。
942+
943+
### 责任链模式
944+
945+
*责任链模式* 也许可以被看作一个使用了 *策略* 对象的“递归的动态一般化”。此时我们进行一次调用,在一个链序列中的每个策略都试图满足这个调用。这个过程直到有一个策略成功满足该调用或者到达链序列的末尾才结束。在递归方法中,一个方法将反复调用它自身直至达到某个终止条件;使用责任链,一个方法会调用相同的基类方法(拥有不同的实现),这个基类方法将会调用基类方法的其他实现,如此反复直至达到某个终止条件。
946+
947+
除了调用某个方法来满足某个请求以外,链中的多个方法都有机会满足这个请求,因此它有点专家系统的意味。由于责任链实际上就是一个链表,它能够动态创建,因此它可以看作是一个更一般的动态构建的 `switch` 语句。
948+
949+
在上面的 `StrategyPattern.java` 例子中,我们可能想自动发现一个解决方法。而 *责任链* 就可以达到这个目的:
950+
951+
```java
952+
// patterns/chain/ChainOfResponsibility.java
953+
// Using the Functional interface
954+
// {java patterns.chain.ChainOfResponsibility}
955+
package patterns.chain;
956+
import java.util.*;
957+
import java.util.function.*;
958+
959+
class Result {
960+
boolean success;
961+
List<Double> line;
962+
Result(List<Double> data) {
963+
success = true;
964+
line = data;
965+
}
966+
Result() {
967+
success = false;
968+
line = Collections.<Double>emptyList();
969+
}
970+
}
971+
972+
class Fail extends Result {}
973+
974+
interface Algorithm {
975+
Result algorithm(List<Double> line);
976+
}
977+
978+
class FindMinima {
979+
public static Result leastSquares(List<Double> line) {
980+
System.out.println("LeastSquares.algorithm");
981+
boolean weSucceed = false;
982+
if(weSucceed) // Actual test/calculation here
983+
return new Result(Arrays.asList(1.1, 2.2));
984+
else // Try the next one in the chain:
985+
return new Fail();
986+
}
987+
public static Result perturbation(List<Double> line) {
988+
System.out.println("Perturbation.algorithm");
989+
boolean weSucceed = false;
990+
if(weSucceed) // Actual test/calculation here
991+
return new Result(Arrays.asList(3.3, 4.4));
992+
else
993+
return new Fail();
994+
}
995+
public static Result bisection(List<Double> line) {
996+
System.out.println("Bisection.algorithm");
997+
boolean weSucceed = true;
998+
if(weSucceed) // Actual test/calculation here
999+
return new Result(Arrays.asList(5.5, 6.6));
1000+
else
1001+
return new Fail();
1002+
}
1003+
static List<Function<List<Double>, Result>>
1004+
algorithms = Arrays.asList(
1005+
FindMinima::leastSquares,
1006+
FindMinima::perturbation,
1007+
FindMinima::bisection
1008+
);
1009+
public static Result minima(List<Double> line) {
1010+
for(Function<List<Double>, Result> alg :
1011+
algorithms) {
1012+
Result result = alg.apply(line);
1013+
if(result.success)
1014+
return result;
1015+
}
1016+
return new Fail();
1017+
}
1018+
}
1019+
1020+
public class ChainOfResponsibility {
1021+
public static void main(String[] args) {
1022+
FindMinima solver = new FindMinima();
1023+
List<Double> line = Arrays.asList(
1024+
1.0, 2.0, 1.0, 2.0, -1.0,
1025+
3.0, 4.0, 5.0, 4.0);
1026+
Result result = solver.minima(line);
1027+
if(result.success)
1028+
System.out.println(result.line);
1029+
else
1030+
System.out.println("No algorithm found");
1031+
}
1032+
}
1033+
/* Output:
1034+
LeastSquares.algorithm
1035+
Perturbation.algorithm
1036+
Bisection.algorithm
1037+
[5.5, 6.6]
1038+
*/
1039+
```
1040+
1041+
我们从定义一个 `Result` 类开始,这个类包含一个 `success` 标志,因此接收者就可以知道算法是否成功执行,而 `line` 变量保存了真实的数据。当算法执行失败时, `Fail` 类可以作为返回值。要注意的是,当算法执行失败时,返回一个 `Result` 对象要比抛出一个异常更加合适,因为我们有时可能并不打算解决这个问题,而是希望程序继续执行下去。
1042+
1043+
每一个 `Algorithm` 接口的实现,都实现了不同的 `algorithm()` 方法。在 `FindMinama` 中,将会创建一个算法的列表(这就是所谓的“链”),而 `minima()` 方法只是遍历这个列表,然后找到能够成功执行的算法而已。
7921044

7931045
<!-- Changing the Interface -->
7941046
## 接口改变

0 commit comments

Comments
 (0)