Follow the public account “Java backend technology full stack” reply “000” to obtain the necessary e-book programmers

Hello everyone, I am Tian, today I will share with you the facade pattern in the design pattern. Describe the design pattern with appropriate life stories and real project scenarios, and finally summarize the design pattern in one sentence.

The story

Those of you who are developers know that backend development is usually:

controller—servie—dao/mapper/repository

But, I’ve asked a lot of people, are they familiar with the facade? Some work for five years without knowing it.

Today, Mr. Tian will take you to see the facade pattern.

Overview of facade patterns

A Facade Pattern, also known as a Facade Pattern, provides a unified interface to access a set of interfaces in a subsystem. Its main feature is to define a high-level interface to make the subsystem easier to use, belonging to the structural design pattern.

English:

Provide a unified interface to a set of interfaces in asubsystem.Facade defines a higher-level interface that makes thesubsystem easier to use.

In fact, we all use facade patterns a lot in our daily coding work, consciously or unconsciously. Whenever a high-level module needs to schedule multiple subsystems (more than two classes of objects), we will consciously create a new class to encapsulate these subsystems and provide a streamlined interface so that the high-level module can more easily call the functions of these subsystems indirectly.

Case in Life

About the facade mode, in the case of life, very much.

Case 1: You go to the bank to handle business, and a receptionist receives you. Then, the receptionist will ask you what business you need to handle, and he will take you through it one by one, so that we don’t need to shuffle around and look for the corresponding business window. This front desk person is the equivalent of the facade mode.

Case 2: We build a house, if there is no contractor, then you have to find a plumber, electrician, decorator, etc. But if you have a contractor, you don’t have to do these jobs, you tell the contractor directly, you need an electrician to do the wiring. This contractor can be understood as a facade model.

Case 3: The controller we developed at the back end can also be interpreted as a facade mode. For example, to obtain user account information, first check UserService to obtain user information, and then check UserAccountService to obtain user account information.

Application scenario of the facade mode

In the software system, the facade mode applies to the following application scenarios.

  • Provides a concise interface for external access to a complex module or subsystem.

  • When you want to improve subsystem independence.

  • When the subsystem may have bugs or performance-related problems due to unavoidable temporary causes, facade mode can provide a high-level interface to isolate direct interaction between the client and the subsystem and prevent code contamination.

General notation for facade mode

Use code to implement a simple facade pattern, because our favorite place to start is demo.

Business scenario: Now we need to call the respective methods of the three services:

// Public id: Java backend technology full stack
public class ServiceA {
    public void doA(a){
        System.out.println("do ServiceA"); }}public class ServiceB {
    public void doB(a){
        System.out.println("do ServiceB"); }}public class ServiceC {
    public void doC(a){
        System.out.println("do ServiceC"); }}Copy the code

Without the introduction of facade mode, the client is called like this:

// Public id: Java backend technology full stack
public class Client {
    public static void main(String[] args) {
        ServiceA serviceA=new ServiceA();
        ServiceB serviceB=new ServiceB();
        ServiceC serviceC=newServiceC(); serviceA.doA(); serviceB.doB(); serviceC.doC(); }}Copy the code

Each time, the client itself needs to create many service objects. If there are many services involved, the code would be awkward. There is a lot of repetitive code.

The results

do ServiceA
do ServiceB
do ServiceC

Copy the code

Let’s add the facade mode:

// Public id: Java backend technology full stack
public class Facade {
    // Is it similar to injecting services into controller?
    private ServiceA serviceA = new ServiceA();
    private ServiceB serviceB = new ServiceB();
    private ServiceC serviceC = new ServiceC();

    public void doA(a) {
        serviceA.doA();
    }

    public void doB(a) {
        serviceB.doB();
    }

    public void doC(a) { serviceC.doC(); }}Copy the code

The client becomes:

public class Client {
    public static void main(String[] args) {
        // Just create the facade object
        Facade facade=newFacade(); facade.doA(); facade.doB(); facade.doC(); }}Copy the code

Running results:

do ServiceA
do ServiceB
do ServiceC
Copy the code

Facade pattern UML diagrams

Combined with this UML diagram, it is easier to understand the facade pattern when reviewing the case of bank front desk staff and contractor.

Characters in facade mode

As you can see from the image above, the facade mode mainly consists of two characters.

  • Facade: Also known as a Facade role, it is a unified interface to the system.

  • Subsystem roles (Services) : You can have one or more services at the same time. Each Service is not a single class, but a collection of classes. Services do not know that a Facade exists; to services, a Facade is just another client (that is, a Facade is transparent to ServiceA, ServiceB, and ServiceC).

Extension of facade mode

advantages

Low reduce system depend on each other Think about it, if we do not use the facade pattern, outside access directly into the internal subsystem, is a kind of strong coupling relationship between each other, you die I will die, can you live my live, it is strongly dependent on the system design is unacceptable, the appearance of the facade pattern is well solved the problem, All dependencies are on facade objects, independent of subsystems.

● Increased flexibility As dependency decreases, flexibility naturally increases. No matter what happens inside the subsystem, as long as it doesn’t affect the facade object, you can do whatever you want.

● Improve security want to let you access the subsystem of what business to open what logic, not open methods on the facade, you can not access.

disadvantages

  • When adding subsystem and extending subsystem behavior, it can be easy to introduce unknown risks.

  • Inconsistent with the opening and closing principle.

  • In some cases, the principle of single responsibility may be violated.

How are the great gods used

There is also a lot of use of facade patterns in Spring, for example

org.springframework.jdbc.support.JdbcUtils
Copy the code

And let’s look at how it works

public static void closeConnection(@Nullable Connection con) {
    con.close();
}
public static Object extractDatabaseMetaData(DataSource dataSource, DatabaseMetaDataCallback action)
   throws MetaDataAccessException {
    Connection con = null;
  try {
   con = DataSourceUtils.getConnection(dataSource);
   DatabaseMetaData metaData = con.getMetaData();
   if (metaData == null) {
      / /...
   }
   returnaction.processMetaData(metaData); }}...Copy the code

All the methods are wrapped for me. For us developers, I only face the JdbcUtils class. I don’t have to worry about how Connection, ResultSet and other things are created.

Mybatis also uses facade mode, for example:

org.apache.ibatis.session.Configuration
Copy the code

Methods that start with new in Configuration, such as:

public Executor newExecutor(Transaction transaction) {
    return newExecutor(transaction, defaultExecutorType);
}
public MetaObject newMetaObject(Object object) {
    return MetaObject.forObject(object, objectFactory, objectWrapperFactory, reflectorFactory);
}

public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {...return parameterHandler;
}

public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler, ResultHandler resultHandler, BoundSql boundSql) {...return resultSetHandler;
}

public StatementHandler newStatementHandler(Executor Executor, MappedStatement MappedStatement) {... }Copy the code

Where these methods are called, he doesn’t know how to new the object, just use it.

There are also facade modes in Tomcat, such as:

org.apache.catalina.connector.RequestFacade

Copy the code

You can tell by the name that it uses facade mode. It encapsulates a lot of request operations and also incorporates a lot of content outside of servlet-API, making it very easy for users to use. Tomcat also wraps ResponseFacade and Standardssession Facade classes for Response and Session.

PS: Almost any class that ends on a Facade uses the Facade pattern.

Reference: Tom’s design Patterns course

conclusion

Ok, so much about the facade mode to share, after reading this article do you feel that the facade mode is actually very simple, in addition to work can also consider whether it can be used, at the same time, the interview can also be used to blow.

Finally, one sentence is used to summarize the appearance mode:

Open a door to the world.

Well, that’s all for today’s strategy patterns.

Look forward to your likes, forwarding, thank you!