曹耘豪的博客

委托模式

委托模式,就是一个类将部分功能(也可以是全部功能)委托给另一个类

比如一个机器人(Person),可以说(speak)也可以听(hear

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
interface SpeakDelegate { void speak(String text); }
interface HearDelegate { void hear(String text); }

class Robot {
SpeakDelegate speakDelegate;
HearDelegate hearDelegate;
void speak(String text) { speakDelegate.speak(text); }
void hear(String text) { hearDelegate.hear(text); }
}

class MyRobotBehaviour implements SpeakDelegate, HearDelegate {
String name = 'Jack';

void speak(String text) {
System.out.format('My name is %s. I speak %s\n', name, text)
}

void hear(String text) {
System.out.format('My name is %s. I hear %s\n', name, text)
}
}

Robot robot = new Robot();
MyRobotBehaviour myRobotBehaviour = new MyRobotBehaviour()
robot.speakDelegate = myRobotBehaviour;
robot.hearDelegate = myRobotBehaviour;

当然也可以全权委托,看起来和代理类似,但代理一般是不能变更被代理的对象的,而委托可以修改委托对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
interface RobotDelegate { void speak(String text); void hear(String text); }

class Robot {
RobotDelegate delegate;
void speak(String text) { delegate.speak(text); }
void hear(String text) { delegate.hear(text); }
}

class MyRobotBehaviour implements RobotDelegate {
String name = 'Jack';

void speak(String text) {
System.out.format('My name is %s. I speak %s\n', name, text)
}

void hear(String text) {
System.out.format('My name is %s. I hear %s\n', name, text)
}
}

Robot robot = new Robot();
MyRobotBehaviour myRobotBehaviour = new MyRobotBehaviour()
robot.delegate = myRobotBehaviour;
   /