Java design pattern: appearance pattern; java Design Pattern appearance
I. Introduction
The appearance mode (Facade) hides the details and complexity of internal subsystems and provides the client with the same Calling Interface, making the complex system easy to access and use.
In simple terms, the appearance mode combines complex subsystems into an interface for customers to use. For example, three important roles are involved:
1. subsystem role: implement the logical functions of the subsystem. The client is unknown, and subsystems can interact with each other.
2. Portal role: core role. For the client to call, familiar with internal subsystem functions. Combine functions of subsystems according to customer needs and abstract them into an interface.
3. Customer role: Call the Facade interface to complete the functions to be implemented
Ii. Practice
Suppose there is a villa with many doors, such as bedroom doors, hall doors, and kitchen doors. The host must close these doors before leaving the house. The general practice is to close them one by one. If the appearance mode is used, A general switch is provided to control all doors.
First, define an interface for closing the door:
public interface Door { public void closeDoor();}
Create a category for the bedroom Door, hall Door, and kitchen Door to implement the Door interface:
public class BedroomDoor implements Door { public void closeDoor() { System.out.println("closing bedroom door."); }}
public class KitchenDoor implements Door { public void closeDoor() { System.out.println("closing kitchen door."); }}
public class HallDoor implements Door { public void closeDoor() { System.out.println("closing hall door."); }}
Door class, which combines or merges various door closing operations to provide only unique Interfaces
public class DoorFacade { Door bd = new BedroomDoor(); Door kd = new KitchenDoor(); Door hd = new HallDoor(); public void closeDoor() { bd.closeDoor(); kd.closeDoor(); hd.closeDoor(); }}
The client can close all the doors by calling the interface of the door class.
public class Client { public static void main(String[] args) { DoorFacade facade = new DoorFacade(); facade.closeDoor(); }}
Running result:
Iii. Advantages
1. Loose coupling: decouples the client and subsystem, making it easier to expand and maintain the module functions inside the subsystem;
2. ease of use: the client does not need to know the implementation of the subsystem or the composition of the subsystem. It only needs to interact with the Facade class;
3. Better access layers: some methods are external to the system, and some methods are used to interact with each other within the system. The subsystem puts the functions exposed to the outside into the facade, so that the client can be used and the internal details of the Child system can be well hidden.