GOF23设计模式(十一)

GOF设计模式之中介者模式(Mediator)与命令模式(Command)

中介者模式(Mediator)

定义一个中介对象来封装一系列对象之间的交互,使原有对象之间的耦合松散,且可以独立地改变它们之间的交互。中介者模式又叫调停模式,它是迪米特法则的典型应用。

职责接口

1
2
3
4
public interface Mediator {
void register(String dname,Department d);
void command(String dname);
}

部门接口

1
2
3
4
5
//同事类接口
public interface Department {
void selfAction(); //做本部门的事情
void outAction(); //发出申请
}

研发部

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Development implements Department{
private Mediator m; //持有中介者的引用

public Development(Mediator m) {
this.m = m;
m.register("development", this);
}

@Override
public void selfAction() {
System.out.println("开发项目");
}

@Override
public void outAction() {
System.out.println("研发部汇报工作");
}
}

财务部

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Finacial implements Department{
private Mediator m; //持有中介者的引用

public Finacial(Mediator m) {
this.m = m;
m.register("finacial", this);
}

@Override
public void selfAction() {
System.out.println("数钱");
}

@Override
public void outAction() {
System.out.println("财务部汇报工作");
}
}

市场部

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Market implements Department{
private Mediator m; //持有中介者的引用

public Market(Mediator m) {
this.m = m;
m.register("market", this);
}

@Override
public void selfAction() {
System.out.println("调研接项目");
}

@Override
public void outAction() {
System.out.println("市场部汇报工作");
m.command("finacial");
}
}

总管理

1
2
3
4
5
6
7
8
9
10
11
12
public class President implements Mediator{
private Map<String,Department> map=new HashMap<>();
@Override
public void register(String dname, Department d) {
map.put(dname,d);
}

@Override
public void command(String dname) {
map.get(dname).selfAction();
}
}

测试

1
2
3
4
5
6
7
8
9
10
11
public class Client {

public static void main(String[] args) {
Mediator m=new President();
Market market=new Market(m);
Development devp=new Development(m);
Finacial f=new Finacial(m);
market.selfAction();
market.outAction();
}
}

测试

调研接项目
市场部汇报工作
数钱

命令模式(Command)

将请求封装为一个对象,从而使我们可用不同的请求对客户端进行参数化。

执行者

1
2
3
4
5
6
7
8
9
/**
* 真正的执行者
*
*/
public class Receiver {
public void action() {
System.out.println("Receiver.action()");
}
}

命令接口及实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* 返回一个结果为空的方法
* 根据实际需求可以写多个不同方法
*/
public interface Command {
void execute();
}

class ConcreteCommand implements Command{
private Receiver receiver;

public ConcreteCommand(Receiver receiver) {
this.receiver = receiver;
}

@Override
public void execute() {
//自行添加相关处理
receiver.action();
}
}

调用

1
2
3
4
5
6
7
8
9
10
11
public class Invoke {
private Command command;

public Invoke(Command command) {
this.command = command;
}
//业务方法,调用命令类的方法
public void call() {
command.execute();
}
}

测试

1
2
3
4
5
6
7
8
9
public class Client {

public static void main(String[] args) {
Command c=new ConcreteCommand(new Receiver());
Invoke i=new Invoke(c);
i.call();
//new Receiver().action();
}
}

结果

Receiver.action()

原创技术分享,您的支持将鼓励我继续创作
0%