Preface

《 Design mode study room 》 series , seeing the name of a thing one thinks of its function , This series takes you through common design patterns . The main contents are :

  • Introduction of the mode , Include :
  • Introduction 、 Intention ( Big white explanation )
  • Class diagram 、 Sequence diagram ( Theoretical norm )
  • Code example for this pattern : Be familiar with the code of this pattern
  • The advantages and disadvantages of this model : The model is not all gold , Don't abuse patterns
  • The application case of this pattern : Know what important source code it is used in

A review of the series

  • 【 Design mode study room 】 The opening : Why do we use design patterns ?
  • 【 Design mode study room 】 Builder pattern
  • 【 Design mode study room 】 Archetypal model
  • 【 Design mode study room 】 A thorough understanding of the singleton pattern
  • 【 Design mode study room 】 Understand the three forms of the factory model
  • 【 Design mode study room 】 Adapter pattern
  • 【 Design mode study room 】 unsung hero : Decoration mode
  • 【 Design mode study room 】 Bridging mode Bridge Pattern: Dealing with multidimensional change

Structural type —— Appearance mode / Facade mode Facade Pattern

Introduction

Facade mode is to encapsulate some complex processes into an interface for external users to use more simply .

For example, users use computers , The computer works : Power on, power off, restart, etc . Every operation has complicated logic , For example, you need to start first BIOS- Boot hard disk — Entry system - Initialize desktop, etc . For users , Just call the boot method .
【 Design mode study room 】 Facade mode  Facade Pattern

Definition

Facade mode ( Facade Pattern) It's also called appearance mode , Is a more commonly used packaging mode ,

Provide a unified interface to a set of interfaces in a subsystem.Facade defines a higher-level interface that makes the subsystem easier to use.( It is required that the external and internal communication of a subsystem must be carried out through a unified object . The facade pattern provides a high-level interface , Makes the subsystem easier to use .)

Class diagram

If you don't understand UML Class diagram , You can browse the picture roughly first , If you want to know more about it , Can continue Google , Learn more :
【 Design mode study room 】 Facade mode  Facade Pattern

Facade pattern class diagram :
【 Design mode study room 】 Facade mode  Facade Pattern

  • Customer role (Client): The customer calls Facede To complete the function to be realized .
  • The role of the facade (Facade): It is called by the client role , And know the subsystems you're managing . The interior has ordered several function combinations according to the needs of the customer's role .
  • Subsystem role (SystemA/B/C): The function of the subsystem is realized . It's completely transparent to the customer's role . It can have interaction within the system , It can also be called by an external interface .

Sequence diagram

Sequence diagram (Sequence Diagram) Is a graph showing the interaction between objects , These objects are arranged in chronological order . The sequence diagram shows the objects involved in the interaction and the order of message interaction between them .

We can roughly browse the sequence diagram , If you are interested in it, you can go deep into it :
【 Design mode study room 】 Facade mode  Facade Pattern

Code implementation

The facade Facade:

public class Computer
{
    public static final Logger LOGGER = Logger.getLogger(Computer.class);

    private CPU cpu;
    private Memory memory;
    private Disk disk;
    public Computer()
    {
        cpu = new CPU();
        memory = new Memory();
        disk = new Disk();
    }
    public void start()
    {
        LOGGER.info("Computer start begin");
        cpu.start();
        disk.start();
        memory.start();
        LOGGER.info("Computer start end");
    }

    public void shutDown()
    {
        LOGGER.info("Computer shutDown begin");
        cpu.shutDown();
        disk.shutDown();
        memory.shutDown();
        LOGGER.info("Computer shutDown end...");
    }
}

Client calls Client:

public class Client
{
    public static final Logger LOGGER = Logger.getLogger(Client.class);

    public static void main(String[] args) {

        Computer computer = new Computer();
        computer.start();
        computer.shutdown();
    }

For users , Use Client There's no need to care about the underlying details .

Use scenario example

A typical example :SLF4J Appearance patterns in

SLF4J It's a simple framework for log appearance patterns , Abstracts various logging frameworks, such as Logback、Log4j、Commons-logging and JDK Self contained logging Implementation interface . It allows users to use the logging framework they want when they deploy .

SLF4J No replacement for any logging framework , It's just the look and feel pattern of the standard logging framework . If you have a classpath other than SLF4J There's no more logging framework , Then the default state is to output log on the console .
【 Design mode study room 】 Facade mode  Facade Pattern

Spring JDBC Appearance patterns in

see org.springframework.jdbc.support.JdbcUtils

Mybatis Appearance patterns in

see org.apache.ibatis.session.Configuration Class new Opening method

public class Configuration {
    public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
        executorType = executorType == null ? defaultExecutorType : executorType;
        executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
        Executor executor;
        if (ExecutorType.BATCH == executorType) {
          executor = new BatchExecutor(this, transaction);
        } else if (ExecutorType.REUSE == executorType) {
          executor = new ReuseExecutor(this, transaction);
        } else {
          executor = new SimpleExecutor(this, transaction);
        }
        if (cacheEnabled) {
          executor = new CachingExecutor(executor);
        }
        executor = (Executor) interceptorChain.pluginAll(executor);
        return executor;
    }

    public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,
          ResultHandler resultHandler, BoundSql boundSql) {
        ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);
        resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
        return resultSetHandler;
    }
    // ... Omit ...
}

Tomcat Appearance patterns in

org.apache.catalina.connector.Request and org.apache.catalina.connector.RequestFacade Both classes implement HttpServletRequest Interface

Advantages and disadvantages

advantage

  • Loose coupling : Decouple between client and subsystem , Make it easier to expand and maintain the module functions within the subsystem ;
  • Simple and easy to use : The client does not need to know the internal implementation of the subsystem at all , Or you don't need to know the composition of the subsystem at all , It just needs to follow Facade Class interaction .
  • Better division of access levels : Some methods are for out of system , Some methods are used interactively within the system . The subsystem concentrates the functions that are exposed to the outside world into the facade , In this way, the client can be used , It's a good way to hide the details inside the subsystem .

shortcoming

  • Without introducing Abstract appearance classes , Adding a new subsystem may need to modify the appearance class or the client's source code , Contrary to “ Opening and closing principle ”.

Reference resources

Pay attention to me

I'm a back-end development engineer .

Focus on back-end development , Data security , Reptiles , The Internet of things , Edge calculation, etc , Welcome to exchange .

I can be found on all platforms

  • WeChat official account : Back end technology
  • Github:@qqxx6661
  • CSDN:@ Back end technology
  • You know :@ Back end technology
  • Simple books :@ Back end technology
  • Nuggets :@ Back end technology

The main content of the original blog

  • Java Review the whole manual for interview knowledge points
  • Design patterns / data structure Self-Study Room
  • Leetcode/ The finger of the sword offer Algorithm problem analysis
  • SpringBoot/SpringCloud Rookie introduction series
  • Reptile related technical articles
  • Back end development related technical articles
  • anecdote / Share good books / Personal interests

Official account number : Back end technology

【 Design mode study room 】 Facade mode  Facade Pattern
official account : Back end technology .jpg

If it helps you , May as well collect , Coin-operated , forward , It looks like ~