The role of the Facade Pattern:

  • Loose coupling: The facade pattern loosens the coupling between the client and the subsystem, allowing the modules inside the subsystem to be more easily extended and maintained.

  • Simple and easy to use: The facade pattern makes the subsystem easier to use. The client no longer needs to understand the internal implementation of the subsystem, nor does it need to interact with many internal modules of the subsystem; it only needs to interact with the facade class.

  • Better layering of access levels: Through the reasonable use of Facade, it can help us better divide the access levels. Some methods are exposed to the outside of the system, and some are used internally. Concentrating the functions that need to be exposed to the outside into the facade makes it convenient for clients to use and also hides the internal details well.

Roles of the Facade Pattern:

  • SubSystem: Subsystem role. Represents a subsystem or module of a system.

  • Facade: Facade role. The client achieves the purpose of controlling the subsystem role by operating the facade role. For the client, the facade role is like a barrier that shields the client from the specific implementation of the subsystem.

Case Study

Suppose a computer contains the following components: CPU (processor), Memory, and Disk. To start the computer, the CPU, Memory, and Disk must be started in sequence. The same applies to shutting down.

But in reality, when we turn the computer on/off, we don't need to operate these components at all, because the computer has already handled everything for us and hidden these details.

These components are like the subsystem roles, and the computer 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 address: https://blog.csdn.net/u012420654/article/details/60332995