


I have been working for five years and I still don't understand the facade model!
Aug 28, 2023 pm 03:11 PMOkay, 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) { //輕輕松松的搞定,只需要創(chuàng)建門面這個對象即可 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.
● 提高安全性 想讓你訪問子系統(tǒng)的哪些業(yè)務(wù)就開通哪些邏輯,不在門面上開通的方法,你休想訪問到 。
缺點
當(dāng)增加子系統(tǒng)和擴(kuò)展子系統(tǒng)行為時,可能容易帶來未知風(fēng)險。 不符合開閉原則。 某些情況下,可能 違背單一職責(zé)原則
。
大神們是如何使用的
在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); } } ......
都是給我封裝好了方法,對于我們開發(fā)者來說,我只面向JdbcUtils
這一個類就好了,我不用去管Connection
、ResultSet
等是怎么創(chuàng)建的,需要的時候,我調(diào)用JdbcUtils
的對應(yīng)方法即可獲得對應(yīng)的對象。
在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){ ... }
對于調(diào)用這些方法的地方,他并不知道是怎么new
出來的對象,只管使用就行了。
在Tomcat
中也有門面模式,比如:
org.apache.catalina.connector.RequestFacade
從名字就知道它用了門面模式。它封裝了非常多的request
操作,也整合了很多servlet-api
以外的內(nèi)容,給用戶使用提供了很大便捷。同樣,Tomcat
針對Response
和Session
也封裝了對應(yīng)的ResponseFacade
類和StandardSessionFacade
類,感興趣的小伙伴可以深入了解一下。
PS
:基本上所有以Facade
結(jié)尾的類,都是使用到了門面模式。
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

Undress AI Tool
Undress images for free

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

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

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

The difference between HashMap and Hashtable is mainly reflected in thread safety, null value support and performance. 1. In terms of thread safety, Hashtable is thread-safe, and its methods are mostly synchronous methods, while HashMap does not perform synchronization processing, which is not thread-safe; 2. In terms of null value support, HashMap allows one null key and multiple null values, while Hashtable does not allow null keys or values, otherwise a NullPointerException will be thrown; 3. In terms of performance, HashMap is more efficient because there is no synchronization mechanism, and Hashtable has a low locking performance for each operation. It is recommended to use ConcurrentHashMap instead.

Java uses wrapper classes because basic data types cannot directly participate in object-oriented operations, and object forms are often required in actual needs; 1. Collection classes can only store objects, such as Lists use automatic boxing to store numerical values; 2. Generics do not support basic types, and packaging classes must be used as type parameters; 3. Packaging classes can represent null values ??to distinguish unset or missing data; 4. Packaging classes provide practical methods such as string conversion to facilitate data parsing and processing, so in scenarios where these characteristics are needed, packaging classes are indispensable.

StaticmethodsininterfaceswereintroducedinJava8toallowutilityfunctionswithintheinterfaceitself.BeforeJava8,suchfunctionsrequiredseparatehelperclasses,leadingtodisorganizedcode.Now,staticmethodsprovidethreekeybenefits:1)theyenableutilitymethodsdirectly

The JIT compiler optimizes code through four methods: method inline, hot spot detection and compilation, type speculation and devirtualization, and redundant operation elimination. 1. Method inline reduces call overhead and inserts frequently called small methods directly into the call; 2. Hot spot detection and high-frequency code execution and centrally optimize it to save resources; 3. Type speculation collects runtime type information to achieve devirtualization calls, improving efficiency; 4. Redundant operations eliminate useless calculations and inspections based on operational data deletion, enhancing performance.

Instance initialization blocks are used in Java to run initialization logic when creating objects, which are executed before the constructor. It is suitable for scenarios where multiple constructors share initialization code, complex field initialization, or anonymous class initialization scenarios. Unlike static initialization blocks, it is executed every time it is instantiated, while static initialization blocks only run once when the class is loaded.

InJava,thefinalkeywordpreventsavariable’svaluefrombeingchangedafterassignment,butitsbehaviordiffersforprimitivesandobjectreferences.Forprimitivevariables,finalmakesthevalueconstant,asinfinalintMAX_SPEED=100;wherereassignmentcausesanerror.Forobjectref

Factory mode is used to encapsulate object creation logic, making the code more flexible, easy to maintain, and loosely coupled. The core answer is: by centrally managing object creation logic, hiding implementation details, and supporting the creation of multiple related objects. The specific description is as follows: the factory mode handes object creation to a special factory class or method for processing, avoiding the use of newClass() directly; it is suitable for scenarios where multiple types of related objects are created, creation logic may change, and implementation details need to be hidden; for example, in the payment processor, Stripe, PayPal and other instances are created through factories; its implementation includes the object returned by the factory class based on input parameters, and all objects realize a common interface; common variants include simple factories, factory methods and abstract factories, which are suitable for different complexities.

There are two types of conversion: implicit and explicit. 1. Implicit conversion occurs automatically, such as converting int to double; 2. Explicit conversion requires manual operation, such as using (int)myDouble. A case where type conversion is required includes processing user input, mathematical operations, or passing different types of values ??between functions. Issues that need to be noted are: turning floating-point numbers into integers will truncate the fractional part, turning large types into small types may lead to data loss, and some languages ??do not allow direct conversion of specific types. A proper understanding of language conversion rules helps avoid errors.
