Skip to content

Commit 4fe7ca0

Browse files
committed
构建应用程序框架
1 parent 1dc1a75 commit 4fe7ca0

File tree

2 files changed

+50
-2
lines changed

2 files changed

+50
-2
lines changed

docs/book/25-Patterns.md

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ public class SingletonPattern {
7878
} catch(Exception e) {
7979
throw new RuntimeException(e);
8080
}
81-
}
81+
}
8282
} /* Output: 47 9 */
8383
```
8484
创建单例的关键是防止客户端程序员直接创建对象。 在这里,这是通过在Singleton类中将Resource的实现作为私有类来实现的。
@@ -103,6 +103,54 @@ public class SingletonPattern {
103103
<!-- Building Application Frameworks -->
104104
## 构建应用程序框架
105105

106+
应用程序框架允许您从一个类或一组类开始,创建一个新的应用程序,重用现有类中的大部分代码,并根据需要覆盖一个或多个方法来定制应用程序。
107+
108+
**模板方法模式**
109+
110+
应用程序框架中的一个基本概念是模板方法模式,它通常隐藏在底层,通过调用基类中的各种方法来驱动应用程序(为了创建应用程序,您已经覆盖了其中的一些方法)。
111+
112+
模板方法模式的一个重要特性是它是在基类中定义的,并且不能更改。它有时是一个 **private** 方法,但实际上总是 **final**。它调用其他基类方法(您覆盖的那些)来完成它的工作,但是它通常只作为初始化过程的一部分被调用(因此框架使用者不一定能够直接调用它)。
113+
114+
```Java
115+
// patterns/TemplateMethod.java
116+
// Simple demonstration of Template Method
117+
118+
abstract class ApplicationFramework {
119+
ApplicationFramework() {
120+
templateMethod();
121+
}
122+
123+
abstract void customize1();
124+
125+
abstract void customize2(); // "private" means automatically "final": private void templateMethod() { IntStream.range(0, 5).forEach( n -> { customize1(); customize2(); }); }}// Create a new "application": class MyApp extends ApplicationFramework { @Override void customize1() { System.out.print("Hello "); }@Override
126+
127+
void customize2() {
128+
System.out.println("World!");
129+
}
130+
}
131+
132+
public class TemplateMethod {
133+
public static void main(String[] args) {
134+
new MyApp();
135+
}
136+
}
137+
/*
138+
Output:
139+
Hello World!
140+
Hello World!
141+
Hello World!
142+
Hello World!
143+
Hello World!
144+
*/
145+
```
146+
147+
基类构造函数负责执行必要的初始化,然后启动运行应用程序的“engine”(模板方法模式)(在GUI应用程序中,这个“engine”是主事件循环)。框架使用者只提供
148+
**customize1()****customize2()** 的定义,然后“应用程序”已经就绪运行。
149+
150+
![](images/designproxy.png)
151+
152+
153+
106154

107155
<!-- Fronting for an Implementation -->
108156
## 面向实施
@@ -161,4 +209,4 @@ public class SingletonPattern {
161209

162210
<!-- 分页 -->
163211

164-
<div style="page-break-after: always;"></div>
212+
<div style="page-break-after: always;"></div>

docs/images/designproxy.png

57.2 KB
Loading

0 commit comments

Comments
 (0)