写在前面
什么是行为型的设计模式
主要是类和对象如何交互,划分相应的责任和算法
为什么要用
不仅解决了类和对象如何划分而且还描述了他们之间如何通信,也是为了更好的完成抽象,保证了代码的扩展性和稳定性,在写代码迷茫纠结的时候让你不迷茫
模式类型
迭代器模式(Iterator)
说明:想遍历聚合对象内所有元素,还不暴露对象内部结构,实际上也相当代理了一层
结构
Aggregate
AggregateImpl
Iterator
ItertorImpl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63// 迭代器
interface Iterator {
// 遍历方法
Object next();
boolean hasNext();
...
}
// 聚合对象
interface Aggregate {
Iterator createIterator();
Object get(int i);
int size();
}
class SelfIterator implements Iterator {
// 交互点
private Aggregate aggregate;
public SelfIterator(Aggregate aggregate) {
this.aggregate = aggregate;
}
private int size = -1;
public Object next() {
if (aggregate.size() - 1 > size) {
size++;
}
return aggregate.get(size);
}
public boolean hasNext() {
if (aggregate.size() - 1 > size) {
return true;
}
return false;
}
}
class SelfAggerator implements Aggregate {
private List list;
public Iterator createIterator() {
return new SelfIterator(this);
}
public Object get(int i) {
return list.get(i);
}
public int size() {
return list.size();
}
}
适用场景
Jdk:Iterable接口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19public interface Collection<E> extends Iterable<E> {
...
}
public interface Iterable<T> {
Iterator<T> iterator();
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
default Spliterator<T> spliterator() {
return Spliterators.spliteratorUnknownSize(iterator(), 0);
}
}Mybatis
Spring
观察者模式(Observer)
- 说明
- 结构
- 适用场景
命令模式(Command)
- 说明
- 结构
- 适用场景
策略模式(Strategy)
- 说明
- 结构
- 适用场景
责任链模式 (Chain of Responsibility)
- 说明
- 结构
- 适用场景
状态模式 (State)
- 说明
- 结构
- 适用场景
模板方法模式(Template)
- 说明
- 结构
- 适用场景
中介者模式(Mediator)