Design mode-Appearance mode

Source: Internet
Author: User

Appearance mode is a very high-frequency structural design pattern, which simplifies the interaction between the client and subsystem by introducing a visual role, provides a unified portal for complex subsystem calls, reduces the coupling between subsystems and clients, and facilitates client invocation.

1. Overview of the Appearance mode

Do not know if you have compared their own tea and tea to teahouse the difference, if it is their own tea needs to prepare tea, tea and boiling water, 1 (A), and to tea in the teahouse, the simplest way is to tell the teahouse waiter want a cup of tea, is Tieguanyin, or West Lake Longjing? Just because the teahouse has a waiter, customers do not have to directly and tea, tea, water and other interactions, the entire tea process by the waiter to complete, customers just interact with the waiter, the whole process is very simple and easy, 1 (B) shown.

Figure 12 Ways of drinking tea

In software development, sometimes in order to complete a more complex function, a customer class needs to interact with more than one business class, and these need to interact with the business class often as a whole, because of the many analogies involved, resulting in the use of the code is more complex, at this time, especially need a waiter-like role, It is responsible for interacting with multiple business classes, and the customer class simply interacts with that class. The appearance mode implements this function by introducing a new appearance class (facade) , which acts as a "waiter" in the software system, providing a unified portal for calls to multiple business classes, simplifying the interaction between classes and class. In appearance mode, those business classes that require interaction are referred to as subsystems (Subsystem). If there is no appearance class, then each customer class needs to interact with multiple subsystems with complex interactions, the system will be very coupled, 2 (A), and after the introduction of the Appearance class, the customer class only needs to directly interact with the appearance class, the original complex reference relationship between the customer class and the subsystem is implemented by the appearance class. This reduces the coupling of the system, as shown in 2 (B).

Figure 2 Appearance mode

in appearance mode, the external and internal communication of a subsystem is carried out through a unified appearance class, which separates the customer class from the internal complexity of the subsystem, so that the customer class only needs to deal with the appearance role, without having to deal with many objects inside the subsystem.

The appearance pattern is defined as follows:

appearance mode: provides a unified portal for a set of interfaces in a subsystem. The appearance pattern defines a high-level interface that makes this subsystem easier to use.

facade Pattern: Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.

Appearance mode, also known as façade mode, is an object-structured pattern. The appearance pattern is a concrete realization of the Dimitri law, which can reduce the complexity of the original system by introducing a new appearance character, and reduce the coupling degree of the customer class and subsystem.

2. Appearance pattern structure and implementation 2.1 pattern structure The appearance pattern does not have a generalized class diagram description, and typically uses 2 (B) to represent the appearance pattern. The class diagram shown in Figure 3 can also be used as a structural diagram describing the appearance pattern:

Figure 3 Appearance mode structure diagram

As shown in Figure 3, the appearance pattern contains the following two characters:

(1) Facade (appearance role): in a way that the client can invoke it, the functions and responsibilities of the related (one or more) subsystems can be known in the appearance role; Under normal circumstances, it delegates all requests from the client to the appropriate subsystems. Passed to the appropriate subsystem object processing.

(2) SubSystem (subsystem role): in a software system can have one or more subsystem roles, each subsystem can not be a separate class, but a collection of classes, it implements the function of the subsystem, each subsystem can be directly called by the client, Or called by the skin role, which handles requests passed by the appearance class, the subsystem does not know the appearance, and for the subsystem, the appearance role is just another client.

2.2 Mode implementation

The main purpose of the appearance mode is to reduce the complexity of the system, in the object-oriented software system, the more the relationship between classes and classes can not indicate that the better the system is designed, it means that the coupling between the classes in the system is too large, so that the system lacks flexibility in maintenance and modification, because the change of one class will cause multiple classes The introduction of the appearance mode greatly reduces the coupling relationship between classes and classes. After introducing the appearance pattern, it is very convenient to add new subsystems or remove subsystems, and the customer classes need not be modified (or rarely modified), simply add or remove references to subsystems in the appearance class. From this point of view, the appearance mode does not conform to the opening and closing principle to a certain extent, and the new subsystem needs to make some changes to the original system, although this modification is not very work.

The subsystem referred to in the appearance pattern is a generalized concept, which can be a class, a function module, an integral part of the system, or a complete system. subsystem classes are typically business classes that implement specific, independent business functions, typically in the following code:

Class Subsystema  {public      void MethodA ()      {          //Business implementation Code      }  }}    class Subsystemb  {      public void MethodB ()      {          //Business implementation Code       }  }    class Subsystemc  {public      void methodc ()      {          //Business implementation Code      }  }  

After the introduction of the Appearance class, the interaction with the subsystem business class is done by the skin class, which usually has the following code in the Appearance class:

Class facade  {      private Subsystema obj1 = new Subsystema ();      Private Subsystemb obj2 = new Subsystemb ();      Private SUBSYSTEMC obj3 = new Subsystemc ();        public void Method ()      {          obj1. MethodA ();          Obj2. MethodB ();          Obj3. METHODC ();      }  }  

Because a reference to a subsystem object is maintained in the skin class, the client can indirectly invoke the business method of the subsystem object through the skin class without having to interact directly with the Subsystem object. After introducing the appearance class, the client code becomes very simple and the typical code is as follows:

Class program  {      static void Main (string[] args)      {          facade facade = new facade ();          Façade. Method ();      }  }  

3. Application example of appearance mode

The following is an example of an application to further learn and understand the appearance pattern.

1. Example Description

a software company to develop a file encryption module that can be applied to multiple software, the module can encrypt the data in the file and store the encrypted data in a new file, the specific process consists of three parts, namely reading the source file, encrypting, saving the encrypted file, where The read file and save file are implemented using a stream, and the cryptographic operation is implemented by the modulo operation. These three operations are relatively independent, in order to achieve the independent reuse of code, so that the design more consistent with the principle of a single responsibility, the three operations of the business code encapsulated in three different classes.

The file encryption module is now designed using the appearance mode.

2. Example Class diagram

Through analysis, this example structure is shown in Figure 4.

Figure 4 File encryption module structure diagram

In Figure 4, Encryptfacade acts as a skin class, and FileReader, Ciphermachine, and FileWriter act as subsystem classes.

3. Instance Code

(1) FileReader: A file read class that acts as a subsystem class.

//filereader.cs using System;  Using System.Text;    Using System.IO;         Namespace Facadesample {class FileReader {public string Read (string filenamesrc) {              Console.Write ("read the file, get clear text:");              FileStream fs = null;         StringBuilder sb = new StringBuilder ();                  try {fs = new FileStream (FILENAMESRC, FileMode.Open);                 int data; while (data = fs. ReadByte ())! =-1) {SB = sb.                 Append ((char) data); } fs.                 Close (); Console.WriteLine (sb.)         ToString ()); } catch (FileNotFoundException e) {Console.WriteLine ("File does not exist!)         "); } catch (IOException e) {Console.WriteLine ("File operation Error!)         "); } return SB.          ToString (); }      }  }  

(2) Ciphermachine: A data encryption class that acts as a subsystem class.

CipherMachine.cs  using System;  Using System.Text;    Namespace Facadesample  {      class ciphermachine      {public         string Encrypt (string plaintext)          {         Console.Write ("Data encryption, converting plaintext to ciphertext:");         String es = "";              char[] chars = Plaintext.tochararray ();         foreach (char ch in chars)               {                  string c = (ch% 7). ToString ();             es + = c;         }              Console.WriteLine (es);         return es;}}  }  

(3) FileWriter: File Save class, act as subsystem class.

FileWriter.cs  using System;  Using System.IO;  Using System.Text;    Namespace Facadesample  {      class FileWriter      {public          void Write (String encryptstr,string filenamedes)           {         Console.WriteLine ("Saves the ciphertext, writes the file. ");              FileStream fs = null;         Try              {                 fs = new FileStream (filenamedes, filemode.create);                  byte[] str = Encoding.Default.GetBytes (ENCRYPTSTR);                  Fs. Write (str,0,str. Length);                  Fs. Flush ();                 Fs. Close ();         }             catch (FileNotFoundException e)               {          Console.WriteLine ("File does not exist!) ");         }         catch (IOException e)               {                  Console.WriteLine (e.message);             Console.WriteLine ("File Operation Error! ");         }                  }      }  }  

(4) Encryptfacade: An encryption appearance class that acts as a skin class.

EncryptFacade.cs  namespace Facadesample  {      class Encryptfacade      {          //maintain references to other objects           private FileReader reader;          Private Ciphermachine cipher;          Private FileWriter writer;            Public Encryptfacade ()          {              reader = new FileReader ();              cipher = new Ciphermachine ();              writer = new FileWriter ();          }            Business method that calls other objects public           void Fileencrypt (String filenamesrc, String filenamedes)          {              string plainstr = Reader. Read (FILENAMESRC);              String encryptstr = cipher. Encrypt (PLAINSTR);              Writer. Write (Encryptstr, filenamedes);}}}    

(5) Program: Client Test class

Program.cs  using System;    Namespace Facadesample  {      class program      {          static void Main (string[] args)          {              Encryptfacade EF = New Encryptfacade ();              Ef. Fileencrypt ("Src.txt", "Des.txt");              Console.read ();}}}    

Compile and run the program with the following output:

Read the file to get clear text: Hello world!

Data encryption, converting plaintext to ciphertext: 233364062325

Save ciphertext, write to file.

In this example, the data in the file Src.txt is encrypted, the content of the file is "Hello world!", after encryption to save the ciphertext to another file Des.txt, the program is saved in the file after the ciphertext is "233364062325". In the cryptographic class Ciphermachine, the clear text is encrypted by the modulo operation, and each character in the clear text is divided by an integer (in this case, 7, which can be set by the user), and the remainder is used as ciphertext.

4. Abstract Appearance class

In a standard appearance pattern structure diagram, if you need to add, delete, or replace a subsystem class that interacts with the skin class, you must modify the source code of the skin class or client, which violates the open and closed principle, so you can improve the system by introducing an abstract appearance class to some extent to solve the problem. After introducing the abstract appearance class, the client can program for the abstract appearance class, and for the new business requirements, there is no need to modify the original appearance class, and the corresponding add a new concrete appearance class to associate the new subsystem object with the new concrete appearance class. At the same time, modify the configuration file to achieve the purpose of not modifying any source code and replacing the skin class.

Here's a concrete example to learn how to use the abstract appearance class:

If you need to replace an encryption class in the application instance "file encryption module", instead of using the original cryptographic class ciphermachine based on the modulo operation, and the new cryptographic class newciphermachine based on the shift operation, the code is as follows:

Using System;              Namespace Facadesample {class Newciphermachine {public string Encrypt (string plaintext) {              Console.Write ("Data encryption, converting plaintext to ciphertext:");              String es = "";              int key = 10;//Set Key, shift number is char[] chars = Plaintext.tochararray ();                  foreach (char ch in chars) {int temp = CONVERT.TOINT32 (CH);                      Lowercase letter Shift if (Ch >= ' a ' && ch <= ' z ') {temp + = key% 26;                      if (temp > 122) Temp-= 26;                  if (temp <) temp + = 26; }//Capital shift if (CH >= ' A ' && ch <= ' Z ') {temp + = key                      % 26;                      if (temp >) Temp-= 26;                  if (temp < n) temp + = 26; } es + = ((char) temp).              ToString (); } Console.WriteLine (ES);          return es;   }      }  }

If you do not add a new appearance class, you can only modify the original appearance class Encryptfacade source code to implement the replacement of the encryption class, the original reference to the Ciphermachine type object to the Newciphermachine type object reference, which violates the open and closed principle, It is therefore necessary to implement changes to the subsystem object reference by adding a new appearance class.

If you add a new appearance class Newencryptfacade to interact with the FileReader class, the FileWriter class, and the newly added Newciphermachine class, although the original System class library does not need to make any modifications, But because the client code originally programmed for the Encryptfacade class, it now needs to be changed to the Newencryptfacade class, so the client source code needs to be modified.

How do you use the new skin class without modifying the client code? One workaround is to introduce an abstract skin class that is programmed by the client for the abstract skin class, and then at run time to determine the specific appearance class , and the file encryption module structure after the introduction of the abstract appearance class is shown in Figure 5:

Figure 5 File encryption module structure diagram after introduction of abstract appearance class

In Figure 5, the client class client is programmed for the abstract appearance class Abstractencryptfacade, and the Abstractencryptfacade code is as follows:

Namespace Facadesample  {      abstract class Abstractencryptfacade      {public          abstract void Fileencrypt ( String filenamesrc, String filenamedes);      }  }  

Add the specific encryption appearance class Newencryptfacade code as follows:

Namespace Facadesample  {      class Newencryptfacade:abstractencryptfacade      {          private filereader reader;          Private Newciphermachine cipher;          Private FileWriter writer;            Public Newencryptfacade ()          {              reader = new FileReader ();              cipher = new Newciphermachine ();              writer = new FileWriter ();          }            public override void Fileencrypt (String filenamesrc, String filenamedes)          {              string plainstr = reader. Read (FILENAMESRC);              String encryptstr = cipher. Encrypt (PLAINSTR);              Writer. Write (Encryptstr, filenamedes);}}}    

The configuration file, app. Config, stores the class name of the specific skin class, with the following code:

<?xml version= "1.0" encoding= "Utf-8"?>  <configuration>    <appSettings>      <add key= " Facade "value=" Facadesample.newencryptfacade "/>    </appSettings>  </configuration>  

The client test code is modified as follows:

Using System;  Using System.Configuration;  Using System.Reflection;    Namespace Facadesample  {      class program      {          static void Main (string[] args)          {              Abstractencryptfacade EF; Programming for abstract Appearance class              //Read config file              string facadestring = configurationmanager.appsettings["facade"];              The reflection generates              the object EF = (abstractencryptfacade) assembly.load ("Facadesample"). CreateInstance (facadestring);              Ef. Fileencrypt ("Src.txt", "Des.txt");              Console.read ();}}}    

Compile and run the program with the following output:

Read the file to get clear text: Hello world!

Data encryption, converting plaintext to ciphertext: Rovvy gybvn!

Save ciphertext, write to file.

The original appearance class Encryptfacade also needs to be the subclass of the abstract appearance class Abstractencryptfacade class, changes the concrete appearance class only then modifies the configuration file, does not need to modify the source code, conforms to the opening and shutting principle.

5. Appearance mode effect and applicable scene

The appearance mode is a very high frequency design pattern, which simplifies the interaction between the client and subsystem by introducing a visual role, provides a unified portal for complex subsystem calls, reduces the coupling between the subsystem and the client, and makes the client invocation very convenient. The appearance mode does not add any new functionality to the system, it simply simplifies the calling interface. In almost all the software can find the application of the appearance mode, such as most B/s system has a home page or navigation pages, most of the C/S system provides a menu or toolbar, where the home page and navigation is the B/s system appearance role, and the menu and toolbar is the C/s system appearance role, Their users can quickly access the subsystem, reducing the complexity of the system. All scenarios involving interacting with multiple business objects can be considered for refactoring using the appearance pattern.

5.1 Mode Advantages

The main advantages of the appearance mode are as follows:

(1) It shields the subsystem components from the client, reduces the number of objects that the client needs to process, and makes the subsystem easier to use. By introducing the appearance pattern, the client code becomes very simple, with very few objects associated with it.

(2) It realizes the loose coupling between the subsystem and the client, which makes the subsystem change does not affect the client that calls it, only needs to adjust the appearance class.

(3) The modification of one subsystem has no effect on other subsystems, and the internal changes of the subsystem will not affect the appearance object.

5.2 Mode Disadvantage

The main drawbacks of the appearance pattern are as follows:

(1) It is not very good to restrict the use of the subsystem class directly by the client, which reduces variability and flexibility if there are too many restrictions on the client Access subsystem classes.

(2) If the design is inappropriate, adding new subsystems may require modifying the source code of the Appearance class, which violates the open and closed principle.

5.3 Mode for scenarios

You can consider using the appearance mode in the following situations:

(1) You can use the appearance mode when you want to provide a simple portal for accessing a complex set of subsystems.

(2) There is a large dependency between the client program and several subsystems. The introduction of the appearance class can decouple the subsystem from the client, thus improving the independence and portability of the subsystem.

(3) In a hierarchical structure, the appearance pattern can be used to define the entrance of each layer in the system, and the layers are not directly related to each other, and the contact is established through the appearance class to reduce the coupling degree between the layers.

From Liu Wei Http://blog.csdn.net/lovelion

Design mode-Appearance mode

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.