When I first started to learn design patterns, I was carried away by 23 design patterns. I wanted to learn them well, but the more I looked at them, the more dizzy I became. After a few years of work, LOOKING back, I have some experience, so I make a summary, and hope to bring a little inspiration to my later friends. The author’s level is limited, if there are mistakes in this article, please forgive me.

First, the way of design pattern

I like the way some gurus categorize knowledge into “tao magics” (also from Taoism). The so-called “Tao”, AS I understand it, refers to the root and the primordium. Its characteristic is highly generalized and all-embracing. The so-called “law”, I understand is the operation of the law, system, rules, its characteristics is to ensure the correct operation of the system; The so-called “art” refers to some methods of doing things, which are characterized by methodical steps. The so-called “instrument” is a number of auxiliary tools.

I specifically mention this point here, because we always learn anything from the tao (top-down) or from the art (bottom-up), and in the study of design patterns, I think it should be top-down. Now many articles on the network, as an introduction, introduction to design patterns one by one, some speaking of detailed will also give some type of “duck”, examples of “factory” and so on, to see the fanfare, practice you back to reality, looking at projects in hand inside a class tuo tuo thousands of lines of code, or feeling do not know how to start? I think the problem is that too much emphasis is placed on the technique, the introduction is very clear, and the actual use is easily reduced to abuse, dare not use, use the wrong point. In fact, the core of the whole design pattern, that is, the way of design pattern, I think is a word – “tear”. Avenue to simple, in fact, whether distributed system, sub-database sub-table, micro-services and so on, when it comes to the end is a “demolition” word, is nothing more than how to dismantle, how to ensure the demolition can maintain the problem. So what is the reflection behind the “demolition”? It is the amount of work required to implement the split, and it is also the complexity of the system with more roles. Many articles have introduced the concepts of “distributed”, “microservices”, “design patterns” and so on and their advantages, but rarely mentioned their defects and problems. In fact, predecessors have long concluded that “there is no silver bullet in software development”, everything has its advantages and disadvantages. For example, a stable old system, there is no new demand, forced to set some design patterns, code transformation, the probability is to go wrong; Or the new system starts “interface oriented” programming, each class has a corresponding interface, this development efficiency is estimated to be unacceptable. This is why I would say that learning design patterns is different from the normal learning path and needs to start with the Tao. That is, to grasp the essence of things, rather than mechanically applying design patterns.

Talk about the design mode of the “law”, we have heard a lot, is the “seven principles”, “high cohesion, low coupling” and so on, at first glance sound in the clouds, in fact, is to tell you how to dismantle the better, because it is the previous experience summarized, so generally in accordance with this guidance to do there is no problem. For example, one day you suddenly come up with a new design pattern beyond the 23 patterns, “Method” can let you know whether the new pattern is reliable, whether it conforms to the specification.

Finally, there are 23 different design patterns. The key to most design patterns is not class diagrams, sample code, etc., but the problem they are proposed to solve. “Art” is very limited, it may appear to solve a specific problem, we take this problem to look at the design pattern, may be relatively simple to understand.

As this diagram illustrates, most design patterns, vertically, introduce a new role to solve a problem; Horizontally, it is split into classes and interfaces, the dependency inversion principle. However, it can also be seen that applying design patterns can lead to a proliferation of code and files, and may even reduce the readability of code.

Ii. Understanding and comprehension of factory model

If we look at the factory model with the above ideas, we will find that the three factory models do not need to be memorized. They are only progressive because the problems they solve are more and more complex, but the essential idea remains the same. Instead of drawing class diagrams or writing sample code, I’ll introduce the factory pattern in two layers: problem and solution.

Simple Factory model
  • Problem: The need to separate create code from class code is a common scenario where we want to use a class but don’t want to instantiate (new) it. Maybe the instantiation is too cumbersome, or maybe there are many similar classes and you want to instantiate them in a uniform place. We usually use some dependency injection framework to do this, but if we don’t use a framework, we can also use the factory pattern.
  • The solution: to design a factory class Class provides the factory to create code, finally it can be instantiated to return the product after class, also can return products corresponding interface, returning to class or interface is not actually, see you need hide implementation details of classes, because this model is the key to the factory this concept.
Factory method pattern
  • Problem: A single factory is not enough. If you use the above model, you may find that the factory produces more than ten different classes. Every time you change one or add one, you need to change the code, and then you need to take out the “dismantle” word.
  • Solution: Add an abstraction layer to the factory class, define a parent class or interface, and split it into child factories that implement the same interface depending on the product implementation. In this way, there are more classes in the system, but the huge single factory is divided into several smaller factories, which is easy to maintain.
Abstract Factory pattern
  • Problem: I have a complex set of classes that are related to each other, and I want to use the factory pattern

    This problem is also the most difficult problem, so LET me draw a simple picture here to express it.Take everyday encryption and decryption as an example, suppose I write four classes, AES256\RSA256 indicates the length of the secret key 256 bits, encryption algorithm is AES\RSA encryption and decryption special tool class; AES512\RSA512 similar, but the length has been increased. We have two categories in the figure, but actually there is another correlation between them, which is the correlation between the length of the secret key. Now I want to use the factory pattern to create classes that are encrypted by AES and then signed by RSA.
  • Solutions:
    1. How about a simple factory model?

      Sure, I’ll design an AES factory based on the parameters passed inkey_lenReturns 256 or 512 lengths; Design an RSA factory, based on the parameters passed inkey_lenReturns 256 or 512 lengths. Initialize AES factory first, then RSA factory. In the future, if there is a need to use RC4 algorithm to encrypt again, we need to add a RC4 factory.
    2. How about the factory method model? Of course you can, but it’s more complicated without solving any problems.
    3. Abstract Factory pattern

      Think again about the requirements: AES encryption -> RSA signature. The best way to do this is through a factory class, which selects the key length dimension:
          class 256Factory {
              newAES()
              newRSA()
          }
          class 512Factory {
              newAES()
              newRSA()
          }
          
          func main(){
              Factory f = new 256Factory()
              f.newAES().Encrypt()
              f.newRSA().Sign()
          }
      Copy the code

      If you need to use the RC4 algorithm, add the ·new· method to Factory. Therefore, the abstract factory method solves the problems of complex classes and the correlation between classes. But the essence of the idea is the idea of the simple factory model. At the same time, it can be seen that a problem can have more than one solution, the most awesome solution will be more complex, but it depends on the specific situation.

feeling

Write so much, specially did not draw the class diagram, just feel that it is not necessary to follow the class diagram or sample code to achieve, called XX mode, otherwise it is not the use of “art” multiplication. Let’s look at what problem this pattern is designed to solve, as long as it solves the problem without violating the seven principles of software design. In addition to the factory mode exemplified in the article, other design mode ideas are similar with minor differences. In the same words, learning design mode should start from mastering the “Tao”, and should not learn too early, otherwise it is easy to design mode for design mode.

Recommended reading

Design pattern introduction (I think the most detailed)