Java Design Patterns – Facade Pattern
Category Programming Techniques
The Role of the Facade Pattern:
-
Loose Coupling, the Facade pattern loosens the coupling between the client and the subsystem, making it easier to extend and maintain the modules within the subsystem.
-
Simplicity and Ease of Use, the Facade pattern makes the subsystem more user-friendly. The client no longer needs to understand the internal implementation of the subsystem, nor does it need to interact with numerous modules within the subsystem; it only needs to interact with the Facade class.
-
Better Access Level Division - By using Facade reasonably, it can help us better divide the levels of access. Some methods are for external use, while others are for internal system use. Concentrating the functions that need to be exposed to the outside in the Facade not only facilitates client use but also effectively hides the internal details.
The Roles in the Facade Pattern:
-
SubSystem: Subsystem role. Represents a subsystem or module of a system.
-
Facade: Facade role, the client operates the Facade to control the subsystem. For the client, the Facade acts as a barrier, shielding the client from the specific implementation of the subsystem.
Example Exploration
Suppose a computer contains components such as CPU (processor), Memory (RAM), and Disk (hard drive). To start the computer, you must start the CPU, Memory, and Disk in sequence. The same applies to shutting down.
However, in reality, we do not need to operate these components when turning the computer on or off because the computer has already handled everything for us and hidden these details.
These components are like the subsystem role, and the computer itself is a facade role.
SubSystem Subsystem Role
public class CPU {
public void startup(){
System.out.println("cpu startup!");
}
public void shutdown(){
System.out.println("cpu shutdown!");
}
}
public class Memory {
public void startup(){
System.out.println("memory startup!");
}
public void shutdown(){
System.out.println("memory shutdown!");
}
}
public class Disk {
public void startup(){
System.out.println("disk startup!");
}
public void shutdown(){
System.out.println("disk shutdown!");
}
}
Facade Facade Role
public class Computer {
private CPU cpu;
private Memory memory;
private Disk disk;
public Computer(){
cpu = new CPU();
memory = new Memory();
disk = new Disk();
}
public void startup(){
System.out.println("start the computer!");
cpu.startup();
memory.startup();
disk.startup();
System.out.println("start computer finished!");
}
public void shutdown(){
System.out.println("begin to close the computer!");
cpu.shutdown();
memory.shutdown();
disk.shutdown();
System.out.println("computer closed!");
}
}
The specific call is as follows:
Computer computer = new Computer();
computer.startup();
computer.shutdown();
>
Original article link: https://blog.csdn.net/u012420654/article/details/60332995
** Click to Share Notes
-
-
-