23 design patterns (1)-Facade Design Patterns

Source: Internet
Author: User
Preface

Once I met a requirement that interface A has a method void methoda () and Class B needs to implement the methoda () method of interface, in addition, in Class B, the result obtained by the internal processing logic of the methoda () method must be persisted using a method of class C instance. Since the technical skills are not strong enough, I thought it was impossible to meet this requirement. I began to struggle with two difficulties: 1. the return value of the methoda () method is void, and I cannot obtain the data obtained by the internal logic of methoda, the persistence Class C cannot be used for processing. 2. The input parameter of the methoda () method is empty, and the persistence Class C cannot be injected. At that time, I was overwhelmed. Fortunately, I suddenly remembered the template class design pattern I met when I learned spring, so I learned the template class design pattern to easily solve this problem. Solution: B is defined as an abstract class, and another abstract method absmethod (C) is defined internally. The input parameter of B is of the persistent Class C type () call this abstract method absmethod (C) in the method, so that the persistence class is injected into the methoda () method, and the data in the method can be persisted. Then, you only need to use Class D to inherit Class B and implement the absmethod (c) Method of class B. In this way, you can indirectly pass the C instance to the methoda () method.
This blog does not explain the template design pattern, but emphasizes how important the design pattern is to implement or learn the technical source code by solving the problem. Start text.

Design Pattern principles


The following six design principles are directly Excerpted from other blog posts or Baidu. The final sources of these contents are basically design patterns. The classic book "design patterns-reusable basis for Object-Oriented Software"
1. Open and Close principles(Open Close principle)
The principle of opening/closing is to open the extension and disable the modification. When the program needs to be expanded, you cannot modify the original code to achieve a hot swapping effect. So in a word, it is easy to maintain and upgrade the program to make it more scalable. To achieve this, we need to use interfaces and abstract classes. We will mention this in the specific design.
2. Lee's replacement principle(Liskov substitution principle)
Liskov substitution principle LSP is one of the basic principles of object-oriented design. In the Rys replacement principle, subclasses can certainly appear where any base class can appear. LSP is the cornerstone of inheritance reuse. Only when the primary class can replace the base class and the functions of the software unit are not affected can the base class be reused, the category class can also add new behaviors based on the base class. The Li's replacement principle is a supplement to the "open-closed" principle. The key step for implementing the "open-close" principle is abstraction. The inheritance relationship between the base class and sub-classes is the specific implementation of abstraction. Therefore, the Li's replacement principle is the standard for the specific steps to implement abstraction.
3. Dependency reversal Principle(Dependence inversion principle)
This is the basis of the open/closed principle. The specific content is: True interface programming, dependent on abstraction and not on specifics.
4. Interface isolation principle(Interface segregation principle)
This principle means that using multiple isolated interfaces is better than using a single interface. We can see from this that the design mode is a software design idea, starting from the large-scale software architecture, for the convenience of upgrading and maintenance. So it appears many times above: reducing dependencies and reducing coupling.
5. dimit's Law(Minimum knowledge principle) (DEMETER principle)
What is the principle of least understanding? That is to say, an entity should interact with other entities as little as possible so that the system function modules are relatively independent.
6. Principles of merging and reuse(Composite Reuse Principle)
The principle is to use synthesis/aggregation as much as possible, rather than inheritance.

Problem description

Communication is very lacking for programmers. We need to exercise more. Let's take this example. When someone says a word to us, we need to understand what others mean. Roughly speaking, this process is mainly the result of cooperation between ears and the brain. Your ears must first "listen" to what others say, that is, get what others say to us. Then we can give it to the brain for analysis, so that we can understand that the simulation with code is as follows.

No design mode

Ear class

Package COM. facade. tradition;/***** @ author DC **/public class ear {/***** what others say */private string words; /*** listen-Get what others say */Public String getwords (string words) {system. out. println ("what others say to me:" + words); Return words;}/*** send words to the brain */Public Boolean sendwordstobrain (brain, string words) {return brain. sendwordsinbrain (words );}}

Brain class

Package COM. facade. tradition;/***** @ author DC **/public class brain {/***** discourse */private string words;/***** record discourse to the brain, if someone else says this, set true. Otherwise, false */Public Boolean sendwordsinbrain (string words) {This. words = words; If (words = NULL) {return false;} else {return true;}/*** analysis discourse */Public void explainwords () {// simulate the analysis process try {system. out. println ("analyzing what the other party says ...... "); thread. sleep (5000);} catch (interr Uptedexception e) {e. printstacktrace ();} system. Out. println ("yes, you mean it !! ");}}

Test class testtradition
Let's test, when someone says a word to us, if you want to understand others, what if you don't adopt the facade mode.

Package COM. facade. tradition;/*** do not use the design mode, use code to simulate the process of communicating with others to answer and understand others * @ author DC **/public class testtradition {public static void main (string [] ARGs) {// This is my ear and brain EAR = new ear (); brain = new brain (); // someone else said something to me, I heard the string words = ear. getwords ("what are you doing? "); // But my ears don't understand what others mean, So I handed it to my brain ear. sendwordstobrain (brain, words); // my brain analyzes the discourse brain. explainwords ();}}

With the cooperation of my ears and my brain, I finally understood others' words. The running results are as follows:

Analysis:
Let's take a look at the testtradition code. Have you found that we have to complete all the logic code, but we have to do the logic processing in our ears and the logic processing in our brains. This causes several obvious problems:
1. The test class is seriously coupled with the subsystem represented by the ear class and that represented by the brain class.
2. Our testing class not only interacts with subsystems represented by each class, but also must understand the internal implementation of the classes of the two subsystems.
3. All methods of classes in our system are exposed to the test class, whether exposed or not.
Let's take a look at the software development design principles mentioned above. Are these problems seriously against some design principles. In addition, we do not need to understand and operate some internal methods of the ear or brain. To solve these problems, you can adopt the facade design mode, that is, the facade design mode of this blog.

Facade Design Mode

The ear and brain classes are the same as above.
Head class: Here we add a facade class, that is, the core class of the design pattern. In fact, as a facade, do you not think there is no more appropriate class than head? Head encapsulates ear and brain. Define the head as the door class. The Code is as follows:

Package COM. facade. pattern; import javax. swing. plaf. synth. synthspinnerui;/*** simulate the door class. The door class is generally single-instance, in this example, a simple Singleton ** @ author DC **/public class head {/*** ear reference variable */Public EAR = NULL is designed; /*** brain reference variable */public brain = NULL;/*** header reference variable */public static head = NULL; Private head () {EAR = new ear (); brain = new brain ();}/*** obtain the head header Singleton * @ return */public static head getinstance () {synchronized (head. class) {If (Head = NULL) {return new head () ;}return head ;}} /*** "listen" and then understand the discourse */Public void explainwords (string words) {// someone else said something to me, I heard the string yourwords = ear. getwords (words); // However, my ears do not understand what others mean, so they are handed over to my brain ear. sendwordstobrain (brain, yourwords); // my brain analyzes the discourse brain. explainwords ();}}

Test class testfacade:

Package COM. facade. pattern;/*** use the design pattern, use code to simulate the process of communicating with others to answer and understand others * @ author DC **/public class testfacade {public static void main (string [] ARGs) {// header reference. The specific subsystems and their implementation details are encapsulated in the internal head = head. getinstance (); // as someone else said, I understand that it is not necessary to directly interact with the ear and the brain head. explainwords ("what are you doing ?? ");}}

The running status is the same as that of the design mode.

Analysis:
Let's take a look at what happened this time. The head facade class encapsulates the ear and brain into the interior, and encapsulates a lot of logic processing into the interior. For example, the ear instance obtains the discourse and the ear instance transmits the discourse, all the logic processing methods for the record discourse of the brain instance. Through this portal class, only the explicit words () method for direct interaction with users is exposed to users. Other logical methods are internal methods of the system, therefore, users do not need to be exposed without interaction. In this way, several problems that do not adopt the facade design pattern are solved. Do you think this design mode is simple?

Facade Design Mode



Facade facade role: the client interacts with facade. This role knows the functions and responsibilities of the relevant (one or more) sub-systems. When the client wants to interact with many subsystems, the facade role delegates all requests sent from the client to the corresponding subsystem.
Subsystem sub-system role: You can have one or more sub-systems at the same time. Every subsystem is not a separate class, but a collection of classes. Each subsystem can be called directly by the client or by the facade role. The subsystem does not know the existence of the facade. For the subsystem, the facade is just another client.

The facade mode provides a concise and consistent interface for various subsystems (or structures and methods) to hide the complexity of subsystems and make them easier to use. Facade often faces multiple classes or other program units. By reorganizing various types and program units, it provides a unified interface/interface. The facade mode requires that the external communication of a sub-system and its internal communication must be performed through a unified facade object.

Several Use Cases of the facade mode:
1. When you want to provide a simple interface for a complex subsystem. Subsystems tend to become more and more complex as they evolve. In most modes, More and smaller classes are generated. This makes subsystems more reusable and easier to customize, but it also brings some difficulties for users who do not need to customize subsystems. Facade can provide a simple default view, which is sufficient for most users, and users who need more customization can bypass the facade layer.
2. There is a large dependency between the implementation part of the client program and the abstract class. Introducing facade to separate this subsystem from customers and other subsystems can improve the independence and portability of the subsystem.
3. When you need to build a layered sub-system, use the facade mode to define the entry points for each layer of the sub-system. If the sub-systems are mutually dependent, you can make them communicate only through facade, thus simplifying the dependency between them.

Special note:

1. In the gof book, it is pointed out that in the facade mode, only one facade class is required, and this facade class has only one instance. In other words, it is a singleton class. Of course, this does not mean that there is only one portal class in the entire system, but only one portal class for each subsystem. In other words, if a system has several subsystems, each subsystem has a portal class, and the entire system can have several portals.
2. It is wrong for beginners to think that new behaviors can be added to the subsystem by inheriting a facade class. The facade model is intended to provide a centralized and simplified communication channel for the subsystem, rather than adding new behaviors to the subsystem.

For more professional descriptions, see books and other blog posts. Simply put, we do not adopt the facade design model, just like the current wedding, which is the same as the whole process of the ancient wedding.
Do not use facade design mode = modern wedding.
Now you have met a favorite girl, who is in love, and plans to marry her. You have to give a gift at home. There are many details about this process. After all, how can the daughter of another person, the husband and mother, make you feel so easy and have a dizzy cry.
Facade design mode = ancient wedding.
The wedding as stipulated in the week's ceremony is mainly divided into six steps. First, the man asks the matchmaker to bring a gift to the lady's house to ask for a kiss, and then waits for the woman's house to answer the question. If yes, let the matchmaker take the birthdate of both men and women to Bu jizang. If you can get married and select another day, it is time for the man and the matchmaker to bring a gift to marry. This is convenient. Everything is handed over to the matchmaker, and we cannot determine whether the other party is a female or not. If we have something to do, find the matchmaker. The matchmaker will give us feedback after receiving any news from the girl.
You can understand it by yourself. You can write this because of limited technology and understanding. Thank you !!

Reference books or blog posts:
1. Design Patterns-reusable basics of object-oriented software (Good Book)
2. Facade mode of Java design mode (appearance Mode)
3. Java Design Pattern 19-facade (appearance pattern)
4. Explanation of 23 design modes in Java Development (for example)
5. Design Pattern (15)-Facade Pattern

23 design patterns (1)-Facade Design Patterns

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.