What
门面模式(Facade Design Pattern),也叫外观模式,他是为子系统提供一组统一的接口,定义一组高层接口让子系统更易用。理解起来比较容易,比如系统A含有a、b、c、d四个接口,而系统B需要依次调用这个四个接口完成业务需求,那么,就可以利用门面模式将系统A的这4个接口封装成一个接口接供系统B调用。
Why
应用门面模式,有以下几点优势:
- 解决易用性问题,门面模式可以用来封装系统底层实现,隐藏系统复杂性,提供一组更加简单易用、更高层的接口。
- 解决性能问题,利用门面模式可以将多次接口调用替换为一个门面接口调用,减少网络通信成本,提高客户端的响应速度。
How
门面模式实现很简单,就是对现有接口的二次封装。今天,我们就以大数据任务调度系统中任务的创建、配置和上线为例来介绍门面模式的实现。大数据任务调度系统,你可以理解为集大数据任务开发、调试、上线等功能于一体的一种一站式大数据解决方案。
- 首先,我们先定义以下Task类。
public class Task {
// task id
Long id;
// task's command
String command;
// task.config
String config;
public void setDeployed(Boolean deployed) {
this.deployed = deployed;
}
Boolean deployed;
public Task(Long id, String command) {
this.id = id;
this.command = command;
}
public Long getId() {
return id;
}
public String getCommand() {
return command;
}
public String getConfig() {
return config;
}
public void setConfig(String config) {
this.config = config;
}
@Override
public String toString() {
return String.format("Task{id=%d, command='%s', config='%s', deploy=%s}",
id, command, config, deployed);
}
}
然后,我们定义下TaskService接口和TaskServiceImpl类,主要涉及3个接口——create,config和deploy。
public interface TaskService {
Task create(Long id, String command);
void config(Task task, String config);
void deploy(Task task);
}
public class TaskServiceImpl implements TaskService {
@Override
public Task create(Long id, String command) {
return new Task(id, command);
}
@Override
public void config(Task task, String config) {
task.setConfig(config);
}
@Override
public void deploy(Task task) {
task.setDeployed(true);
}
}
接下来,我们定义TaskController类。
public class TaskController {
private TaskService taskService;
public TaskController(TaskService taskService) {
this.taskService = taskService;
}
public Task create(Long id, String command) {
return this.taskService.create(id, command);
}
public void config(Task task, String config) {
this.taskService.config(task, config);
}
public void deploy(Task task) {
taskService.deploy(task);
}
// facade design pattern
public Task createUntilDeploy(Long id, String command, String config) {
Task task = taskService.create(id, command);
taskService.config(task, config);
taskService.deploy(task);
return task;
}
}
TaskController类中的createUntilDeploy方法就是利用门面模式实现了将三个接口封装为一个大接口,供外部系统调用。
最后,写个测试类,搞定~
public class TestMain {
public static void main(String[] args) {
TaskService taskService = new TaskServiceImpl();
TaskController taskController = new TaskController(taskService);
// A
Task task = taskController.create(1L, "select * from t;");
taskController.config(task, "config somthing");
taskController.deploy(task);
System.out.println(task);
// facade for B
taskController.createUntilDeploy(2L, "select * from t;", "config somthing");
System.out.println(task);
}
}
输出为:
Task{id=1, command='select * from t;', config='config somthing', deploy=true}
Task{id=2, command='select * from t;', config='config somthing', deploy=true}
代码地址
写在最后
如果你觉得我写的文章帮到了你,欢迎点赞、评论、分享、赞赏哦,你们的鼓励是我不断创作的动力~
网友评论