preface

Although single has its own reasons for being single, it doesn’t translate as “single dog”. The English equivalent of “single dog” is “damn Single”, pronounced as a homonym for the Chinese character for “single dog”. The literal translation is “damn single”.

A single brother asked me: What are design patterns?

Design patterns? Let’s say, in life, we often see boys chasing girls, for girls, “being chased” may be a frequent problem; For boys, always chasing others, this is a recurring problem.

Notice, for these repeated problems, the former people have left a variety of “precious” experience, teach boys how to chase girls step by step, teach girls how to prevent and identify boys.

A great deal of this so-called practice leads to patterns, and as you can see, sometimes these “patterns” work very well and help us solve problems very quickly. These patterns are probably called design patterns.

Oh, oh, I see!

In fact, there are some typical problems that are repeatedly encountered in any activity, and different developers devise different solutions to these problems. As design experience becomes more widely used among practitioners, the descriptions of these common problems and solutions to these problems become known as patterns.

The primary role of design patterns

My brother asked me, why do we use design patterns?

This brings us to the role of design patterns.

Just now we have said that various emotional masters have left a lot of valuable emotional experience. What is the use of these so-called “routines”? They can help us quickly catch up with girls, help us quickly identify men who cheat and play with women’s feelings and so on.

For example, how should a boy chase a girl?

(1) You can talk to her first and see if she can talk to you.

(2) Ask her out on a weekend if she gets on well with you.

(3) If the date, you take her to dinner, go to the movies, cross the road, that crossing the road how dangerous ah, she is a weak girl, no one to lead, how dangerous, so you should hold her hand.

(4) If she does not refuse you, you just look at the night sky, lamenting the cool autumn night, she is a weak girl, thin clothes, you should decisively give her a warm hug.

(5) At this time you find that a weak girl, is looking at you affectionately, so you new pity, affectionately embrace her, gave her a warm kiss.

Imagine what happens next… .

So what do you see? Some of them are so cliched, but sometimes they smell good.

First of all, it enables us to promote the relationship between men and women quickly.

Second, when your friend asks you what’s going on, you don’t have to say, we made a dinner date on Thursday night for Friday night, where we met, which restaurant we went to, which movie we went to, what movie we saw… .

You can express your relationship simply by saying, “We’re holding hands today.” “Holding hands” is the definition of your relationship, and it’s a quick way to communicate your progress to anyone.

Third, if you don’t know the drill, you can come up to a first date and ask, “Do you have an apartment, what’s your monthly income, what’s your baby’s last name?” I’m sorry, that’s the end of it. But when you go through the process of developing a relationship, you’re less likely to end it.

Do you find that design patterns have so many important effects, which is why they can’t be retained affectionately since ancient times, but are always popular

In actual development, it doesn’t mean THAT I have to be diligent and honest, but you need to know certain design patterns and use them to write elegant code.

The specific benefits of design patterns are:

1. Simplify and speed up design

2. Facilitate communication between developers

3. Reduce risk

4, facilitate the transition to object-oriented technology

Mature software design patterns have the following characteristics

Then my brother asked me, what are the characteristics of design patterns?

I said, did you notice that the first feature of the repertoire, you’ll find it very clever, why should you hold her hand when you’re crossing the street, because the road is dangerous, you owe her hand to keep her safe, to show your manhood. It’s not easy to say no.

The brother mused: It is wonderful, the girl was all about crossing the road, how could she get rid of my Wolf’s claws?

I said, yes, the second characteristic, is universal. You can do this with this girl, and if you break up and you like another girl, you can still use these tricks. Thousands of girls, but one routine.

The brother puzzled of say: these are useful to each girl?

And I said, sure, and the third thing about the design model is that it’s been well documented that a lot of the older generation, they’ve done a lot of emotional practice, they’ve passed on emotional strategies, they’re not just theoretical.

Brother said, I understand, listen to you say so, I think chasing girls is not so complicated.

I said, that’s the fourth feature of the design model, which is simplicity. After you learn it, it can be applied to actual emotional development, which can greatly simplify the pursuit of a girl. You don’t have to sweat and sweat to think about what I should do first, what I should do next and so on. You just need to follow the routine, simple and practical.

So the last thing that you can do is reuse, you know, take me to dinner, go to the movies, you can reuse it every time you go on a date. Maintain and strengthen your relationship once.

That’s the end of the story, let’s get straight to the point and continue with the introduction of design patterns:

So back in real development, design patterns have the following characteristics:

1. Clever: Design patterns are elegant solutions that are distilled from a great deal of practical experience.

2. Generality: Design patterns are generally not dependent on a particular system type, programming language, or application domain; they are generic

3. It has been well proved that design patterns are widely used in practical and object-oriented systems, and they are not just theoretical.

4. Simplicity: Design patterns are usually very simple, involving only a few classes. To build more complex solutions, different design patterns can be combined or mixed with application code

5. Reusable: The way design patterns are documented makes them very easy to use and therefore easy to use on any suitable system.

6, object-oriented: design pattern is the most basic object-oriented mechanism, such as class, object, polymorphism, etc.

Six principles of design patterns

Here are some basic principles of design patterns:

1. Open Close Principle

The open closed principle means: open for extensions, closed for modifications. When the program needs to be extended, you cannot modify the original code to achieve a hot plug effect. In short, to make the program extensible, easy to maintain and upgrade. To achieve this, we need to use interfaces and abstract classes, which will be discussed later in the concrete design.

2. Liskov Substitution Principle

Richter’s substitution principle is one of the basic principles of object-oriented design. Richter’s rule of substitution says that wherever a base class can appear, a subclass must appear. LSP is the cornerstone of inheritance reuse. The base class can be reused only when the derived class can replace the base class and the function of the software unit is not affected. The derived class can also add new behaviors on the base class. Richter’s substitution principle is a complement to the open – close principle. Abstract is the key step to realize the open and close principle, and the inheritance relationship between base class and subclass is the concrete realization of abstraction, so the Richter substitution principle is the specification of the concrete steps to realize abstraction.

3, Dependence Inversion Principle

This principle is the basis of the open closed principle, the concrete content: programming for interfaces that rely on abstraction rather than on concrete.

4. Interface Segregation Principle

This principle means that it is better to use multiple isolated interfaces than a single one. It also has another meaning: reducing coupling between classes. Thus, in fact, design mode is a software design idea that starts from large-scale software architecture and is easy to upgrade and maintain. It emphasizes reducing dependence and coupling.

5. Demeter Principle, also known as the Least Known Principle

The least known principle means that an entity should interact with other entities as little as possible, so that the functional modules of the system are relatively independent.

Composite Reuse Principle

The principle of composite reuse is to use composition/aggregation rather than inheritance whenever possible.

Classification of design patterns

In total, we cover 23 common design patterns.

There are three categories: 5 + 7 + 12 = 23

  • Creation pattern

    • Factory Pattern
    • Abstract Factory Pattern
    • Builder Pattern
    • Prototype Pattern
    • Singleton Pattern
  • Structural mode

    • Adapter Pattern
    • Bridge Pattern
    • Composite Pattern
    • Decorator Pattern
    • Facade Pattern
    • Flyweight Pattern
    • Proxy Pattern
  • Behavioral pattern

    • Chain of Responsibility Pattern
    • Command Pattern
    • Interpreter Pattern
    • Iterator Pattern
    • Mediator Pattern
    • Memento Pattern
    • Observer Pattern
    • State Pattern
    • Strategy Pattern
    • Template Pattern
    • Visitor Pattern

Creation pattern

The creative pattern is the pattern we use to create objects.

The factory pattern

Factory Pattern is one of the most commonly used design patterns in Java. This type of design pattern is the creation pattern, which provides the best way to create objects.

In factory mode, we create objects without exposing the creation logic to the client, and by using a common interface to point to the newly created objects.

Model example: You ask your girlfriend to take care of the mall, which needs to provide customers with all kinds of food. You want to eat Chinese food, the mall only need to open a Chinese restaurant, the Chinese restaurant is the “factory” you want to eat fish flavor pork, you just need to tell the “factory”, you want “fish flavor pork”; You can also have “Kung Pao chicken”. Through this factory, we can provide you with Chinese food.

Builder model

The Builder Pattern uses multiple simple objects to build a complex object step by step. This type of design pattern is the creation pattern, which provides the best way to create objects. Enforce a step-by-step construction process. But we don’t have to know the details of each process.

Mode example: You and your girlfriend go to a Chinese restaurant for dinner. For example, your girlfriend wants to have a scrambled egg. The chef puts oil in the egg first, then turns it over and stir-fry it. There are several steps and sequences that have been defined. How you do it, like do you break the egg before you put it in the pot, or do you break the egg and put it in the pot right away, it may be different from chef to chef, so we don’t have to worry about that.

Abstract Factory pattern

The Abstract Factory Pattern creates other factories around a gigafactory. The gigafactory is also known as the factory of other factories. This type of design pattern is the creation pattern, which provides the best way to create objects.

In the abstract Factory pattern, an interface is a factory responsible for creating a related object, without explicitly specifying their classes. Each generated factory can provide objects according to the factory pattern.

Model example: You and your girlfriend go to the mall, your girlfriend wants to eat Chinese food today, tomorrow she wants to eat Western food, so, a “factory” is not enough. We need different “factories” for Chinese and Western food. From the customer’s perspective, I need to choose a “factory” and a “dish” first. In factory mode: from the customer’s point of view, I just need to pick one “dish”.

The prototype pattern

The prototype pattern allows objects to create custom objects without knowing the exact class of the object to be created and how to create it.

Model example: You take your girlfriend to eat braised chicken and rice. The waiter asks you, do you want medium or light spicy? You said medium spicy. Let’s say the waiter adds two spoonfuls of chillies to a mild yellow braised chicken rice and brings it out to you, saying it’s medium spicy. This process, in fact, is the prototype mode, the prototype is this “not spicy Chicken braised rice”, “medium spicy chicken braised rice” is not spicy on the basis of two spoonfuls of pepper. The waiter who serves your meal probably doesn’t need to know how to make “non-spicy braised chicken rice”. Just a slight difference in spiciness.

Archetypal patterns typically apply to the following scenarios.

  • Objects are the same or similar, that is, only with different attributes.
  • For example, creating an object takes a long time to initialize, consumes too much CPU, or consumes too many network resources. Therefore, you need to optimize resources.
  • Creating an object requires a lot of data preparation or access rights to improve performance or security.
  • This class object is used extensively in the system, and each caller needs to reassign its properties.

The singleton pattern

The simple interest pattern ensures that a class has only one instance, and provides global access to the class to ensure that all objects that use the class instance use the same instance.

Model Example: You tell your girlfriend about your best years as a kid in school because you were so hard to learn in every subject. If you don’t listen, the teacher will take great pains to teach you. The teachers here, it could be multiple teachers. There are many teachers. This is a lot of cases. But when you get home, you don’t listen, you act up, and if you don’t, your dad will beat you with a belt. Your dad here is the singleton pattern. There’s only one real dad.

Structural pattern

Adapter mode

The Adapter Pattern acts as a bridge between two incompatible interfaces. This type of design pattern is structural in that it combines the functionality of two separate interfaces.

Model example: you go to a restaurant with your girlfriend, your girlfriend wants to eat hot pot, and ordered heavy spicy, but you have a bad stomach these days, the doctor told you not to eat heavy spicy. So you ask the waiter for a large glass of water. Every time before you eat it, you rinse it in the water, and it won’t be hot anymore. It used to be a hot pot that only your girlfriend could eat, but now you can eat it with an extra “adaptation” : this glass of water. This is the adapter pattern. Let the heavy spicy hot pot serve both those who do not eat spicy and those who do.

The bridge model

Bridges are used to decouple abstractions from implementations so that they can vary independently. This type of design pattern is structural in that it decouples abstraction and implementation by providing a bridge between them.

This pattern involves an interface that acts as a bridge, making the functionality of the entity class independent of the interface implementation class. These two types of classes can be structurally altered without affecting each other.

It is emphasized here that entity classes and interfaces are independent of each other.

Pattern example: You take your girl friend out for coffee. They have Americano, cappuccino, or latte. The flavors are unsweetened and sweetened. If the cafe wants to satisfy all customers, it has to prepare American sweetened, cappuccino sweetened, latte sweetened, American unsweetened, cappuccino unsweetened, latte unsweetened. There are six kinds of coffee. But really, all we need is three different flavors of coffee, and two different degrees of sweetness. There are five options. Let taste and sweetness be configured independently and decoupled from each other. This is the bridge mode.

Portfolio model

Composite Pattern, also called partial whole Pattern, is used to treat a group of similar objects as a single object. The composite pattern combines objects based on a tree structure, which is used to represent both part and whole hierarchies. This type of design pattern is a structural pattern that creates a tree structure of groups of objects.

This pattern creates a class that contains its own group of objects. This class provides a way to modify the same object group.

Model example: You give your girlfriend a gift, you buy an iPhone, you buy a case, put together is a case of mobile phone. This is the combination model. The gift you gave was an iPhone in a Shell

Decorator mode

The Decorator Pattern allows you to add new functionality to an existing object without changing its structure. This type of design pattern is a structural pattern that acts as a wrapper around existing classes.

This pattern creates a decorator class that wraps the original class and provides additional functionality while preserving the integrity of the class method signature.

Pattern example: You play chicken with your girlfriend. Your girlfriend found a 98K and asked you to give her an 8X mirror. So that’s the decorator pattern. On the basis of the original 98K, added the function of aiming farsightedness, expanded the function of the original 98K. But the original 98K is still intact.

The appearance model

The Facade Pattern hides the complexity of the system and provides clients with an interface through which they can access the system. This type of design pattern is structural in that it adds an interface to an existing system to hide the complexity of the system.

Model example: you take your girl friend to eat braised chicken rice, after ordering dinner, the wife of the owner sent you to the seat. The whole process, as far as you, the customer, are concerned, involves only one owner’s wife, as if the restaurant had only one orderer. You don’t need to know how it’s processed. For clients, the restaurant simplifies the whole process of eating. Only one of the proprietors’ wives will meet you.

The flyweight pattern

The Flyweight Pattern is mainly used to reduce the number of objects created to reduce memory footprint and improve performance. This type of design pattern is a structural pattern that provides a way to reduce the number of objects to improve the object structure required by the application.

The meta-share pattern attempts to reuse existing objects of the same class, and if no match is found, new objects are created.

Example: Your girlfriend has a habit of drinking a glass of water in her bedroom when she gets up early every day, drinking a glass of water on the dining table before lunch, and drinking a glass of water in her study at night. Do you need three cups to drink from? No. All you need is a cup. The share mode is designed to save object creation. But you need to put the cup in a different place for morning, afternoon and evening. This will require additional arrangements. In this way, the share mode increases the complexity of the program, but saves the creation of the cup resource.

The proxy pattern

In the Proxy Pattern, one class represents the functionality of another class. This type of design pattern is structural.

In the proxy mode, we create objects with existing objects to provide functional interfaces to the outside world.

Example: You and your girlfriend don’t want to go grocery shopping this weekend, so you ask your neighbor to do it for you. The whole process of buying vegetables is up to the neighbors. Neighbors take your taste into account when they buy vegetables. This is the proxy pattern.

Behavioral pattern

Chain of Responsibility model

As the name suggests, the Chain of Responsibility Pattern creates a Chain of recipient objects for a request. This pattern decouples the sender and receiver of the request by giving the type of request. This type of design pattern is behavioral.

In this pattern, each receiver typically contains a reference to the other receiver. If an object cannot handle the request, it passes the same request to the next recipient, and so on.

Model example: You propose to your girlfriend, but she can’t make a decision, so she hands the question to her father. The father couldn’t decide, so he gave the question to the mother. Finally mother saw you dressed like a beast, no, dressed like a man, and decided to marry her daughter to you. This model is the chain of responsibility model.

Command mode

Command Pattern is a data-driven design Pattern, which belongs to behavior Pattern. The request is wrapped in the object as a command and passed to the calling object. The calling object looks for a suitable object that can handle the command and passes the command to the corresponding object, which executes the command.

Pattern example: you and girlfriend lie at home, your girlfriend call you to cook, you go to cook, call you to sweep the floor, you sweep the floor. It’s not the same person who gives the order and carries it out. This is the command mode. The command is encapsulated in “you”, your girlfriend only needs to invoke your “command”.

Interpreter mode

The Interpreter Pattern, which provides a way to evaluate the syntax or expressions of a language, is a behavioral Pattern. This pattern implements an expression interface that interprets a particular context. This pattern is used in SQL parsing, symbol processing engines, and so on.

The mediator pattern

Mediator Pattern is used to reduce the complexity of communication between multiple objects and classes. This pattern provides a mediation class that typically handles communication between different classes and supports loose coupling, making code easy to maintain. The mediator pattern is a behavioral pattern.

Pattern examples:

You’re at home with your girlfriend, you don’t want to go out, order takeout. Take-out platforms are intermediaries for food providers and vendors. The cooks don’t need to know exactly how the food is cooked, nor do they need to know the location of the restaurant. The sellers don’t need to know exactly who ate and cooked the food, male or female, etc.

For the cook and the seller, a lot of communication information is hidden from each other. The cook only needs to pay, and the seller only needs to cook.

Memo mode

The Memento Pattern stores a certain state of an object so that it can be restored at an appropriate time. The memo pattern belongs to the behavior pattern.

Model Example: One year, your girlfriend was surprised by your birthday. You prepared a sumptuous dinner, exquisite gifts, and romantic candles. You have this birthday “suit” stuck in your head. The second year, you gave your girlfriend a set of the same “surprise”, angry your girlfriend ran away from home. The “birthday surprise kit” here is really just a memo. You use the memo model. Pull out a copy of the same thing when you need it. But use it flexibly. Otherwise it is wangwang clever plan Ann world, lost the wife and fold soldiers.

Observer model

The Observer Pattern is used when there is a one-to-many relationship between objects. For example, when an object is modified, dependent objects are automatically notified. The observer model belongs to the behavioral model.

This is the most familiar design pattern for all of you.

Model example: You write down your girlfriend’s mood as a state. Whenever your girlfriend is in a “good” mood, your girlfriend tells you that she is happy. This is when you can do whatever you want. But when your girlfriend gets mad, she tells you, “I’m mad.” At this time, you must not hesitate to kneel down, tearful say: “I’m sorry, dear, I was wrong. It’s all my fault, anyway.” This is the observer mode. Your behavior is totally dependent on your girlfriend’s mood.

The state pattern

In the State Pattern, the behavior of a class changes based on its State. This type of design pattern is behavioral.

In state mode, we create objects that represent various states and a context object whose behavior changes as the state object changes.

Model example: Suppose your girlfriend’s mood can be divided into “happy”, “unhappy” and “average”. And she tells you how: “Buying gifts” will change her mood from “average” to “happy,” “buying a bag” will change her mood from “unhappy” to “happy,” and “hooking up” will change her mood from “happy” to “unhappy.” And so on. These three moods are states, and your girlfriend provides you with some ways to change your state. That’s state mode.

The strategy pattern

In the Strategy Pattern, the behavior of a class or its algorithm can be changed at run time. This type of design pattern is behavioral.

In the policy pattern, we create objects that represent various policies and a context object whose behavior changes as the policy object changes. The policy object changes the execution algorithm of the context object.

Model Example: Your girlfriend’s birthday, you want to make her happy, you can take her to “see a movie”, “take her on a trip”, treat her to “dinner”. In order to achieve a result, you can use different methods, which can be interchangeable with each other, which are all strategic patterns.

Template pattern

In Template Pattern, an abstract class exposes a method/Template that executes its methods. Its subclasses can override method implementations as needed, but the calls will be made in the manner defined in the abstract class. This type of design pattern is behavioral.

Model example: I tell you, to get a girlfriend, first “hold hands”, then “hug”, then “kiss”, then “pat… The forehead.. Hand “… . Whether you use your left hand or your right, it doesn’t matter, but the whole process, set a template. Just follow the template.

Visitor pattern

In the Visitor Pattern, we use a Visitor class that changes the execution algorithm of the element class. In this way, the element’s execution algorithm can change as visitors change. This type of design pattern is behavioral. According to the schema, the element object already accepts the visitor object so that the visitor object can process operations on the element object.

The key to the implementation of the Visitor pattern is how do you separate the operations on elements into separate classes

Model example: you have money, you have interests: like girls. But one day. You have a girlfriend. Your girlfriend tells you to say, “I’m broke, I only like guys” to other girls. When it comes to your girlfriend, say, “My money is your money, and you’re the only one I’ll ever love.” This is probably the visitor pattern. Girlfriends and other girls are two types of visitors, and you are different in terms of wealth and sexual orientation.

Afterword.

Forgot to mention, how does a programmer have a girlfriend?

If the examples are not appropriate, please include more.

If you feel a pattern example is inappropriate, feel free to comment.

Favorite friends can help me like and follow, your attention is my biggest motivation.