国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
All development friends know that back-end development is usually: " >Story All development friends know that back-end development is usually:
Facade Pattern (Facade Pattern" >Overview of Facade Pattern Facade Pattern (Facade Pattern
Facade pattern UML diagram" >Facade pattern UML diagram
Roles in Facade Mode" >Roles in Facade Mode
Extension of the facade pattern" >Extension of the facade pattern
Advantages" >Advantages
缺點" >缺點
大神們是如何使用的 " >大神們是如何使用的
Home Java javaTutorial I have been working for five years and I still don't understand the facade model!

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

Aug 28, 2023 pm 03:11 PM
facade mode


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");
    }
}

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


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.

● 提高安全性   想讓你訪問子系統(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針對ResponseSession也封裝了對應(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!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Difference between HashMap and Hashtable? Difference between HashMap and Hashtable? Jun 24, 2025 pm 09:41 PM

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.

Why do we need wrapper classes? Why do we need wrapper classes? Jun 28, 2025 am 01:01 AM

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.

What are static methods in interfaces? What are static methods in interfaces? Jun 24, 2025 pm 10:57 PM

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

How does JIT compiler optimize code? How does JIT compiler optimize code? Jun 24, 2025 pm 10:45 PM

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.

What is an instance initializer block? What is an instance initializer block? Jun 25, 2025 pm 12:21 PM

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.

What is the `final` keyword for variables? What is the `final` keyword for variables? Jun 24, 2025 pm 07:29 PM

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

What is the Factory pattern? What is the Factory pattern? Jun 24, 2025 pm 11:29 PM

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.

What is type casting? What is type casting? Jun 24, 2025 pm 11:09 PM

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.

See all articles