Appearance Mode
definition
Facade mode is also known as facade mode.
It provides a consistent interface for a set of interfaces in a subsystem, defining a high-level interface that makes the subsystem easier to use.
Features
- Facade mode requires that the communication between the internal and external subsystems must be carried out through the unified interface object
- Facade pattern provides a high-level interface that makes subsystems easier to use
Application example of appearance mode
Appearance mode may sound a little unfamiliar, but we often see it
- examples in life
Initially , we need an mp3 to listen to music, an mp4 to watch movies, and a game console to play games. . . Now we can solve these needs with a single computer.
Here, mp3, mp4 and game console are a complete sub-function system in the computer, and the computer is the appearance of the whole system
- development examples
ImageLoder, XUtils, Volley, etc. all use appearance patterns
such as XUitls framework: many modules
For example: Load UI modules, download file modules, network request modules, etc...
Roles in Appearance Mode
- The system provides a unified interface to the outside world
- Subsystem interface
Design and Implementation of Appearance Mode
Example scenario: We design a computer with the functions of listening to music and playing games
Design subsystem:
1) Listen to music, provide an interface for the music listening subsystem, and implement
//接口
ublic interface IMusicServer {
void start();
void running(String musicName);
void stop();
}
//具体类实现
public class MusicServerImpl implements IMusicServer {
@Override
public void start() {
Log.i("main", "开始听音乐");
}
@Override
public void running(String musicName) {
Log.i("main", "听《" + musicName + "》歌曲");
}
@Override
public void stop() {
Log.i("main", "停止听音乐");
}
}
2) Play games, provide game subsystem interfaces and implement them
接口
public interface IGameServer {
void start();
void running();
void stop();
}
实现
public class GameServerImpl implements IGameServer {
@Override
public void start() {
Log.i("main", "开始游戏");
}
@Override
public void running() {
Log.i("main", "运行游戏");
}
@Override
public void stop() {
Log.i("main", "停止游戏");
}
}
Overall system design and implementation: (provide an overall unified interface for clients)
public class Computer {
//外观模式重要特点:持有子系统引用(高层次接口)
private IGameServer gameServer = new GameServerImpl();
private IMusicServer musicServer = new MusicServerImpl();
public void startGame(){
gameServer.start();
gameServer.running();
}
public void stopGame(){
gameServer.stop();
}
public void startMusic(String musicName){
musicServer.start();
musicServer.running(musicName);
}
public void stopMusic(){
musicServer.stop();
}
}
使用:
Computer computer = new Computer();
computer.startGame();
computer.stopGame();
computer.startMusic("阳光总在风雨后");
computer.stopMusic();
从使用上我们能看出,用户不需要关心子系统做了什么,只需要在整体系统中直接执行需要的命令即可,具体实现由子系统实现