(接上一部分)
Façade vs. Command
均强调对某个复杂系统内部提供的功能的“封装”,对外提供简单的 调用接口,简化client的使用,“隐藏”细节 。
Command:强调将指令封装为了“对象”,提供了统一的对外接口
Command:强调将指令封装为了“对象”,提供了统一的对外接口
Façade:没有显式的“对象”,仍然通过类的方法加以调用。
Chain of responsibility(职责链模式)
针对一个请求,可能有多个处理模块
各种不确定 情况存在,不能以“硬编码”的方式指明按何种次序调用处理模块。
避免在请求方和各handler之间的紧耦合:构造 流水线,请求在其上传递,直到被处理为止。
客户端只需在流水线的入口发出请求即可,请求自动在 流水线上传递,直到被处理。
Visitor vs. Chain of Responsibility
Visitor vs. Chain of Responsibility
Visitor vs. Chain of Responsibility
区别1:visitor只定义了一个操作,chain of responsibility定义了一 组操作及其之间的次序
区别2:visitor中,client创建visitor之后传入ADT,ADT再将执行权 delegate到visitor;chain of responsibility中,控制权完全在各个 handler之间流转,ADT(request对象)完全感受不到
面向维修性的构造技术
State Pattern(状态设计模式)
环境类
Context.java
class Context {
private State state; // 维持一个对抽象状态对象的引用
// 设置状态对象
public void setState(State state) {
this.state = state;
}
// 转换状态。这里是不遵守“开闭原则的部分”。要新增新的状态,必须要修改这里的代码。
public void changeValue(int value) {
// 判断属性值,根据属性值进行状态转换
if (value == 0) {
this.setState(new ConcreteStateA());
} else if (value == 1) {
this.setState(new ConcreteStateB());
}
}
public void request() {
// 其他代码
state.handle(this); // 调用状态对象的业务方法
// 其他代码
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
抽象状态类
State.java
abstract class State {
// 声明抽象业务方法,不同的具体状态类可以不同的实现
public abstract void handle(Context context);
}
- 1
- 2
- 3
- 4
具体状态类
ConcreteStateA.java
class ConcreteStateA extends State {
public void handle(Context context) {
System.out.println("当前状态是 A.");
}
}
- 1
- 2
- 3
- 4
- 5
ConcreteStateB.java
class ConcreteStateB extends State {
public void handle(Context context) {
System.out.println("当前状态是B.");
}
}
- 1
- 2
- 3
- 4
- 5
测试类
Client.java
public class Client {
public static void main(String[] args) {
Context c = new Context();
ConcreteStateA state = new ConcreteStateA();
c.setState(state);
c.request();
c.changeValue(1);
c.request();
c.changeValue(0);
c.request();
}
}
Memento Pattern(备忘录设计模式)
Originator:需要“备忘”的类
Caretaker:添加originator的备忘记录和恢复
Memento: 备忘录,记录originator对象的历史状态
Grammar-based construction(语法驱动的构造)
x ::= y? an x is a y or is the empty string
x ::= y+ an x is one or more y
x ::= [abc] is equivalent to x ::= 'a' | 'b' | 'c‘
x ::= [^abc] is equivalent to x ::= 'd' | 'e' | 'f' | ...(表示表示包含括号中未列出的任何字符的长度-1字符串)
x ::= (y z | a b)* an x is zero or more yz or ab pairs
也可以利用分着展开写的方法。