One, foreword

It’s getting cold. Keep warm. Today we are going to talk about design patterns. When we learn Java, we often hear about singletons, multi-singletons, and when we use Spring, the default singletons are used. You hear about “hungry”, “hungry”, these are all descriptions of design patterns. So what are design patterns? What does it mean?

Concepts of design patterns:

Design patterns represent best practices and are generally adopted by experienced object-oriented software developers. Design pattern is a solution to the common problems faced by software developers during software development. These solutions have been developed by numerous software developers over a long period of trial and error

Personal Understanding:

Design pattern is not a kind of technology, but a pattern system that summarizes the experience of designing some solutions in order to realize some functions in the process of project iteration. This system is a summary of the code design experience that has been used repeatedly, known by most people, and classified and catalogued.

Why use design patterns?

Design patterns are used to reuse code, make it easier for others to understand, and ensure code reliability. In the current software design trend, there is no doubt that design patterns have been applied to every project in every company. Design patterns make the coding process truly engineering. Design patterns are the cornerstones of software engineering, like the bricks and stones of a mansion. Project reasonably use of design patterns can perfectly solve the many problems, each mode in reality has a corresponding principle and the matching, each mode is described in a similar in our development process, the various business and constantly recurring problems, and provides the core of the problem solution, that is why design patterns can be widely used.

Second, GOF design mode

Some of you may have heard of “GOF Design Patterns”. Don’t think of GOF as a single person. GOF is a small team of Four people whose full name is “Gang of Four”. GOF Design Patterns is a compilation of Design Patterns that are frequently used in software development by four members of the team in 1994: Elements of Reusable Object-oriented Software The foundation of Reusable Object-oriented Software, the publication of this book also marks that design pattern has formally become an important research branch of Object Oriented software engineering.

Before covering each of GOF’s design patterns, let’s take a look at the six principles of design patterns:

Six principles of design patterns:

** 1. Open Close Principle **

There is an open and closed principle, open for extensions, but closed for modifications. Can be used when the program needs to be extended, but can not modify the original code to achieve the extension.

** 2. Liskov Substitution Principle **

Wherever a base class can appear, a subclass must appear. A base class can only be reused if it can be replaced by a derived class without affecting the functionality of the software unit, and a derived class can add new behavior to the base class. Richter’s substitution principle is a complement to the open – close principle. The key step to realize the open close principle is abstraction, and the inheritance relationship between base class and subclass is the concrete realization of abstraction.

A subclass can extend the functionality of the parent class, but cannot change the functionality of the original parent class. For example, a subclass can replace the place where the parent class has appeared in the code, and the code still works after the replacement.

3. Dependence Inversion Principle **

Programming for interfaces relies on abstraction rather than concrete. The simple explanation is interface oriented programming, “abstract” is the interface or abstract class, “concrete” is the implementation class; Meaning: upper modules should not depend on lower modules, both should depend on their abstractions; Abstractions should not depend on details, details should depend on abstractions; To pass variables or parameters, use abstract classes or interfaces whenever possible.

For example, the interface is responsible for defining the public constructor, the abstract class is responsible for the implementation of the public constructor, and the implementation class accurately implements the business logic

** 4. Interface Segregation Principle **

Developing with multiple interfaces that are isolated from each other is better than using a single interface. The purpose is to reduce the degree of coupling between classes.

** 5. Demeter Principle) **

At least know the principle, as far as possible to reduce the coupling between classes, one entity should minimize the interaction with other entities, so that the system function modules are relatively independent, to prevent high coupling degree.

** Reuse Principle **

It requires that in software reuse, we should first use association relation such as combination or aggregation, and then consider using inheritance relation. If inheritance is to be used, the Richter substitution principle must be strictly followed. The principle of composite reuse and the Principle of Richter’s substitution complement each other. The principle of composite reuse is to integrate the existing object into the new object as a member object of the new object, the new object can call the function of the existing object, so as to achieve reuse.

Programming goals: high cohesion, low coupling

** Design patterns can be divided into the following three types based on purpose: **

1. Create mode: Used to describe how to create objects

2. Structural pattern: Used to describe how classes or objects are arranged into a larger structure

3. Behavioral pattern: It describes how classes or objects work together to accomplish tasks that a single object cannot accomplish alone, and how responsibilities are assigned.

** Design patterns can be divided into two categories based on scope: **

1. Class pattern: Used to deal with relationships between classes and subclasses. These relationships are static, established by inheritance, and determined at compile time.

2. Object mode: Used to deal with relationships between objects, which can be realized by composition or aggregation and can change at run time and be more dynamic.

** Understanding UML class diagrams can help you learn design patterns better, and learning UML class diagrams can help you understand the relationships between classes more quickly **

Third, the UML

What is UML?

  1. UML, short for Unified Modeling Language (UML), is a language tool for software system analysis and design. It helps software developers think and document the results of their ideas.

  2. UML is like a flowchart, with its own set of notations, like mathematical and chemical notations, used to describe the various elements and others in a software model

Relationships between classes, interfaces, implementations, generalizations, dependencies, compositions, aggregations, etc

** You may have seen the following **

** UML diagrams can be divided into three simple categories: **

  1. Use Case Diagram

  2. Static structure diagram: class diagram, object diagram, package diagram, component diagram, deployment diagram

  3. Dynamic behavior diagram: interaction diagram (sequence diagram and collaboration diagram), state diagram, activity diagram

** We mainly study class diagrams **

  1. The Class diagram consists of a number of (static) illustrative model elements (such as classes, packages, and the relationships between them, which are interconnected with their contents). Class diagrams can be organized into (and belong to) packages, showing only relevant content in a particular package.

  2. The Class diagram is the most commonly used UML diagram, showing classes, interfaces, and the static structure and relationships between them. It describes the structural design of a system.

  3. The most basic element of a Class diagram is a Class or interface.

That’s the picture below

The main model elements of the UML class diagram:

1. Class

2. Interface

3. Relationships between classes.

A, classes,

A Class is an abstraction of objects with the same attributes, methods and relations. It encapsulates data and behaviors. It is the basis of OOP and has three characteristics, namely encapsulation, inheritance and polymorphism. In UML, classes are represented by delimited rectangles containing the class name, attributes, and operations.

(1) Class Name (Name) is a string, for example, Student.

(2) Attributes refer to the characteristics of a class, that is, the member variables of a class.

UML is expressed in the following format:

[Visibility] Attribute name: Type [= default value] Example: -name:StringCopy the code

Note: “Visibility” indicates whether the attribute is visible to elements outside the class, including Public, Private, Protected and Friendly. In the class diagram, the attribute is represented by symbols +, -, # and ~ respectively

Operations are actions that can be used by any instance object of a class. They are member methods of a class. UML is expressed in the following format:

[Visibility] Name (parameter list)[: return type] Example: +display():void.Copy the code

The UML representation of the student class is shown below.

Second, the interface

An Interface is a special class that has the structure of a class but cannot be instantiated. It can only be implemented by an implementation class. It contains abstract operations (abstract methods), but no properties (member variables). It describes the visible actions of a class or component. In UML, interfaces are represented by a small circle with a horizontal line. In the figure below, the interface is the class name with a small horizontal circle.

3. The relationship between classes

There are six relationships between classes: dependency, association, aggregation, composition, generalization, and realization

The shape configuration between each relationship is as follows

** 1. Dependencies **

A Dependency relationship is a usage relationship, which is the least coupled way between objects. For example, in Java, a method of one class accesses some methods in another class (dependent class) through local variables, method parameters, or calls to static methods to accomplish some business development.

The dependency relationship is represented by dotted lines with arrows, and the arrows point from the using class to the dependent class (the user). As shown in the figure below, the relationship between people and cars is shown. People drive through the run method of cars.

** 2

Association relation is a reference relation between objects, which is used to represent the relationship between one class of objects and another class of objects. The association can be bidirectional or unidirectional. In UML class diagrams, bidirectional associations can be represented as solid lines with two arrows or no arrows, and one-way associations are represented as solid lines with an arrow pointing from the using class to the associated class. You can also annotate role names at both ends of the association line to represent two different roles.

(1) One-way association, people have the property object of the car.

(2) Two-way correlation, people own the car, and the car has the information attribute of the owner

(3) Self-related, water is made up of countless water molecules, but water molecules are still water

** 3. Aggregation relationship **

Aggregation is a kind of association relation. It is a strong association relation. It is the relation between whole and part, and it is the relation of HAS-A. The whole and the parts can also become separate modules if taken separately, but the whole needs to depend on the parts to ensure the whole. In UML class diagrams, aggregate relationships can be represented by solid lines with hollow diamonds, which point to the whole.

For example, the company and its employees are each independent. If the company disappears, its employees will still be employees. However, the company will cease to exist without its employees.

** 4

Composition is also a kind of association. It is also the whole and part of the relationship between classes, but it is a stronger aggregation of cxmTAINes-A.

In combinatorial relation, the whole object can control the life cycle of some objects. Once the whole object does not exist, some objects will not exist, and some objects cannot exist without the whole object.

In UML class diagrams, composition relationships are represented by solid lines with solid diamonds that point to the whole:

For example, feet are an important part of the human body. If the body does not exist, then feet do not exist, and parts cannot be separated from the whole.

** 5

Generalization relationship is the relationship with the maximum coupling degree between objects, and is the relationship between the parent class and the child class, and is an inheritance relationship and the RELATIONSHIP of IS-A.

In Java, if a parent class is inherited by a subclass, the relationship between the parent class and the subclass is called “generalization relationship”.

In UML class diagrams, generalization relationships are represented by solid lines with hollow triangular arrows that point from subclasses to parent classes. When the code is implemented, the object-oriented inheritance mechanism is used to realize the generalization relationship

For example, as a parent class, people may have multiple subclasses. Authors have human attributes and special writing skills, while readers have the skills to comment on books. In this way, a generalization relationship is formed (human beings and authors, human beings and readers are both generalized relations).

** 6

A Realization relationship is the relationship between an interface and an implementation class. In this relationship, the implementation class implements the abstract methods in the interface, and the operations in the class implement all the abstract operations declared in the interface.

In UML class diagrams, implementation relationships are represented by dashed lines with hollow triangular arrows that point from the implementation class to the interface.

For example, the following figure: a car is an interface and a specification, and it can run if it meets the requirement. Cars and bicycles have realized the “run” method, and cars can now realize automatic driving, which is to realize the “run” method according to the specification of the interface, so the relationship between the interface and the implementation class is the implementation relationship.

The document comes from my public number, I hope you pay attention to it