设计模式(2)结构型模式

结构型模式

桥接模式

将抽象和实现耦合,使得两者可以独立的变化。

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
interface Implementor{

void doSomething();
void doAnything();
}

class ConcreteImplementor1 implements Implementor{

public void doSomething(){
//具体业务处理
}

public void doAnything(){
//具体业务处理
}
}

abstract class Abstraction{

private Implementor imp;

public Abstraction(Implementor _imp){
imp = _imp;
}

//自身的行为和属性
public void request(){
imp.doSomething();
}

public Implementor getImp(){
return imp;
}
}

class RefinedAbstraction extends Abstraction{

public RefinedAbstraction(Implementor _imp){
super(_imp);
}

@Override
public void request(){
super.request();
super.getImp().doAnything();
}
}

class Client{

public static void main(String[] args){
//定义一个实现化角色
Implementor imp = new ConcreteImplementor1();
//定义一个抽象化角色
Abstraction abs = new RefinedAbstraction(imp);
abs.request();
}
}

组合模式

文件系统由文件和目录组成,每个文件里装有内容,而每个目录的内容可以有文件和目录,目录就相当于是由单个对象或组合对象组合而成,如果你想要描述的是这样的数据结构,那么你就可以使用组合模式。

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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
abstract class Component {

public abstract void operation();

public void add(Component c) {
throw new UnsupportedOperationException();
}

public void remove(Component c) {
throw new UnsupportedOperationException();
}

public Component getChild(int i) {
throw new UnsupportedOperationException();
}
}

class ConcreteComponent1 extends Component {

public void operation() {
System.out.println("operation of concrete component 1 ");
}
}

class ConcreteComponent2 extends Component {

public void operation() {
System.out.println("operation of concrete component 2 ");
}
}

class ConcreteComponent3 extends Component {

public void operation() {
System.out.println("operation of concrete component 3 ");
}
}

class Composite extends Component {

private ArrayList<Component> children;

public Composite() {
children = new ArrayList<Component>();
}

public void operation() {
for(Component child: children) {
child.operation();
}
}

public void add(Component c) {
children.add(c);
}

public void remove(Component c) {
children.remove(c);
}

public Component getChild(int i) {
return children.get(i);
}
}

public class Client {

public static void main(String[] args) {

Component c1 = new ConcreteComponent1();
Component c2 = new ConcreteComponent2();
Component c3 = new ConcreteComponent3();

Component c = new Composite();
c.add(c1);
c.add(c2);
c.add(c3);
c.operation();

c.remove(c2);
c.operation();
}
}

享元模式

享元,就是共享元素的意思。

https://zhuanlan.zhihu.com/p/53087983

行为型模式

策略模式

模板方法模式

观察者模式