


I have been working for five years and I still don't understand the facade model!
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
Today, Lao Tian will show you the facade mode.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.
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"); } }
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(); } }
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
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(); } }
The client becomes:
public class Client { public static void main(String[] args) { //轻轻松松的搞定,只需要创建门面这个对象即可 Facade facade=new Facade(); facade.doA(); facade.doB(); facade.doC(); } }
Run Result:
do ServiceA do ServiceB do ServiceC
Facade pattern UML diagram
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 moreService
at the same time. EachService
is not a separate class, but a collection of classes.Service
do not know the existence ofFacade
. To the Service,Facade
is just another client (that is,Facade
isServiceA
,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
再来看看其中的方法
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); } } ......
都是给我封装好了方法,对于我们开发者来说,我只面向JdbcUtils
这一个类就好了,我不用去管Connection
、ResultSet
等是怎么创建的,需要的时候,我调用JdbcUtils
的对应方法即可获得对应的对象。
在Mybatis
中也是用到了门面模式,比如:
org.apache.ibatis.session.Configuration
在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){ ... }
对于调用这些方法的地方,他并不知道是怎么new
出来的对象,只管使用就行了。
在Tomcat
中也有门面模式,比如:
org.apache.catalina.connector.RequestFacade
从名字就知道它用了门面模式。它封装了非常多的request
操作,也整合了很多servlet-api
以外的内容,给用户使用提供了很大便捷。同样,Tomcat
针对Response
和Session
也封装了对应的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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Start Spring using IntelliJIDEAUltimate version...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...
