Home > Java > Java Tutorial > body text

I have been working for five years and I still don't understand the facade model!

Release: 2023-08-28 15:11:34
forward
708 people have browsed it


Okay, let’s get into our topic. Today I will share with you the facade pattern# in the design pattern. ##. Use appropriate life stories and real project scenarios to tell the design pattern, and finally use one sentence to summarize this design pattern.

Story All development friends know that back-end development is usually:

controller---servie---dao/mapper/repository

However, I have asked many people whether they are familiar with the facade mode? Some people have been working for five years and don’t even know.

Today, Lao Tian will show you the facade mode.

Overview of Facade Pattern Facade Pattern (Facade Pattern

) is also called Appearance Pattern , provides a unified interface for accessing a group of interfaces in the subsystem. Its main feature is that it defines a high-level interface to make the subsystem easier to use, and it belongs 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, in daily coding work, we They are all using the facade pattern a lot, intentionally or unintentionally. Whenever a high-level module needs to schedule multiple subsystems (more than two class objects), we will consciously create a new class to encapsulate these subsystems and provide a streamlined interface so that high-level modules can more easily indirectly call the functions of these subsystems.

Cases in life

There are so many cases in life about the facade model.

Case 1: Go to the bank to handle business, and a front desk will receive you. Then, the front desk will ask you what business you need to do, and he will take you through it one by one, so that we don’t need to wander around and go everywhere. Find the corresponding business window. This front desk staff is equivalent to the facade model.

Case 2: When we build a house, if there is no contractor, you will have to find cement workers, electricians, decorators, etc. by yourself. But if you have a contractor, you don't have to do any of these tasks. You can tell the contractor directly that you need an electrician to fix the wiring. This contractor can be understood as a facade model.

Case 3: The controller developed by our backend can also be understood as a facade mode. For example, to obtain user account information, first check UserService to obtain user information, and then Check UserAccountService user account information.

Applicable scenarios for facade mode

In software systems, facade mode is suitable for the following application scenarios.

  • Provide a simple interface for external access to a complex module or subsystem.
  • When you want to improve the independence of the subsystem.
  • When a subsystem may have bugs or performance-related problems due to unavoidable temporary reasons, a high-level interface can be provided through the facade mode to isolate the direct interaction between the client and the subsystem. Prevent code pollution.

General writing method of facade mode

Still use code to implement a simple facade mode , because what we like most is to start with the demo.

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

public class ServiceA {
    public void doA(){
        System.out.println("do ServiceA");
    }
}
public class ServiceB {
    public void doB(){
        System.out.println("do ServiceB");
    }
}

public class ServiceC {
    public void doC(){
        System.out.println("do ServiceC");
    }
}
Copy after login

When the facade mode is not introduced, the client calls it like this:

public class Client {
    public static void main(String[] args) {
        ServiceA serviceA=new ServiceA();
        ServiceB serviceB=new ServiceB();
        ServiceC serviceC=new ServiceC();

        serviceA.doA();
        serviceB.doB();
        serviceC.doC();
    }
}
Copy after login

Every Secondly, the client itself needs to create many service objects. If there are many services involved, wouldn't this code be very embarrassing? There will be a lot of repetitive code.

Run result

do ServiceA
do ServiceB
do ServiceC
Copy after login
Copy after login

Let’s add Facade mode:

public class Facade {
    //是不是很像我们controller里注入各种service?
    private ServiceA serviceA = new ServiceA();
    private ServiceB serviceB = new ServiceB();
    private ServiceC serviceC = new ServiceC();

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

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

    public void doC() {
        serviceC.doC();
    }
}
Copy after login

The client becomes:

public class Client {
    public static void main(String[] args) {
        //轻轻松松的搞定,只需要创建门面这个对象即可
        Facade facade=new Facade();
        facade.doA();
        facade.doB();
        facade.doC();
    }
}
Copy after login

Run Result:

do ServiceA
do ServiceB
do ServiceC
Copy after login
Copy after login

Facade pattern UML diagram


I have been working for five years and I still don't understand the facade model!

## Combined with this UML diagram, when reviewing the cases of bank front desk personnel and contractors, it will be easier to understand the facade pattern.

Roles in Facade Mode

As you can see from the picture above, Facade Mode mainly contains 2 roles.

  • Appearance role (Facade): Also called the facade role, it is the unified external interface of the system.
  • Subsystem role (Service): There can be one or more Service at the same time. Each Service is not a separate class, but a collection of classes. Service do not know the existence of Facade. To the Service, Facade is just another client (that is, Facade is ServiceA, ServiceB, ServiceC transparent).

Extension of the facade pattern

Advantages

● Reduce system interdependence Think about it, if we don't use the facade mode, external access goes directly into the subsystem, and there is a strong coupling relationship between them. If you die, I will die, and if you live, I will live. Such strong dependence is the result of system design. Unacceptable, the emergence of the facade pattern solves this problem very well. All dependencies are on the facade objects and have nothing to do with the subsystem.

● Increased flexibility Dependence is reduced and flexibility is naturally increased. No matter how the subsystem changes internally, as long as it does not affect the facade object, you can move freely.

● 提高安全性   想让你访问子系统的哪些业务就开通哪些逻辑,不在门面上开通的方法,你休想访问到 。

缺点

  • 当增加子系统和扩展子系统行为时,可能容易带来未知风险。
  • 不符合开闭原则。
  • 某些情况下,可能违背单一职责原则

大神们是如何使用的

Spring中也是有大量使用到门面模式,比如说

org.springframework.jdbc.support.JdbcUtils
Copy after login

再来看看其中的方法

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) {
      //.....
   }
   return action.processMetaData(metaData);
  }
}
......
Copy after login

都是给我封装好了方法,对于我们开发者来说,我只面向JdbcUtils这一个类就好了,我不用去管ConnectionResultSet等是怎么创建的,需要的时候,我调用JdbcUtils的对应方法即可获得对应的对象。

Mybatis中也是用到了门面模式,比如:

org.apache.ibatis.session.Configuration
Copy after login

Configuration中以new开头的方法,比如:

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 after login

对于调用这些方法的地方,他并不知道是怎么new出来的对象,只管使用就行了。

Tomcat中也有门面模式,比如:

org.apache.catalina.connector.RequestFacade
Copy after login

从名字就知道它用了门面模式。它封装了非常多的request操作,也整合了很多servlet-api以外的内容,给用户使用提供了很大便捷。同样,Tomcat针对ResponseSession也封装了对应的ResponseFacade类和StandardSessionFacade类,感兴趣的小伙伴可以深入了解一下。

PS:基本上所有以Facade结尾的类,都是使用到了门面模式。

Reference: Tom’s Design Pattern Course

Summary

Okay, I have shared so much about the facade mode. After reading this article, do you think that the facade mode is actually very simple? In addition, you can also consider whether it can be used at work. At the same time, it can also be used to brag during interviews.

The above is the detailed content of I have been working for five years and I still don't understand the facade model!. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:Java后端技术全栈
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!