Design pattern (Design pattern) is a set of classified and cataloged summary of code design experience that is used repeatedly, known to most people. The purpose of using design patterns is to reuse code, make the code easier to understand by others, and ensure code reliability. There is no doubt that design patterns are win-win for ourselves, others, and the system; design patterns make code writing truly engineering; design patterns are the cornerstone of software engineering, just like the structure of a building.
Design patterns (English design patterns) are solutions to recurring problems in object-oriented design. This term was introduced into computer science from the field of architectural design in the 1990s by Erich Gamma and others. The meaning of this term is controversial. Algorithms are not design patterns because algorithms address problem solving rather than design problems. Design patterns usually describe a set of classes and objects that interact closely with each other. Design patterns provide a common language for discussing software design so that the design experience of skilled designers can be grasped by novices and other designers. Design patterns also provide goals for software refactoring.
With the growing interest in design patterns in the software development community, some related monographs have been published, corresponding seminars have been held regularly, and Ward Cunningham invented WikiWiki to communicate design patterns. experience.
Tips: This tutorial will explain the concept of design patterns to you step by step through Java examples. So you need to know something about Javaknowledge.
Expression format
The format for expressing a software design pattern will vary according to different authors, such as divisions and names. The format of commonly used GoF description patterns is roughly divided into the following parts:
Pattern name: Each pattern has its own name, and the pattern name allows us to discuss our design.
Problem: There are specific occasions that recur during object-oriented system design that lead us to adopt a certain pattern.
Solution: The solution to the above problem, its content gives the various components of the design, their relationships, division of responsibilities and collaboration methods.
Alias: A pattern can have more than one name. These names should be noted in this section.
Motivation: In which case this pattern is used is the responsibility of the solution provided in this section (including the problem and the context).
Applicability: In which situations the model is applicable, the background of the model, etc.
Structure: This part of commonly used class diagrams and interaction diagrams illustrates this pattern.
Participants: This section provides a list of classes and objects used in this pattern and the roles they play in the design.
Cooperation: Describes the interaction between classes and objects in this mode.
Impact: The impact of adopting this model on other parts of the software system, such as the impact on the scalability and portability of the system. Impact also includes negative impacts. This section should describe the results, side effects, and trade-offs of using this pattern.
Implementation: This section should describe the implementation of the pattern, some solutions to the pattern, and Possible techniques for the pattern, or suggested ways to implement the pattern.
Example: Briefly describe how to use patterns in a programming language.
Known applications: Implementation examples known in the industry.
Related patterns: This part includes other related patterns and differences from other similar patterns.
Tip: Our Design Patterns tutorial will help you learn all about design patterns. If you have any questions, please go to PHP中文网community to ask your question, and enthusiastic netizens will answer it for you.
Pattern Principles
Everyone is starting to pay attention to design patterns. So, why do we use design patterns? Why should we design with so many design patterns?
To be honest, I really didn’t understand it before. Just watching everyone repeating "Design pattern" makes me feel a little weak. So I bought a book on the design patterns of the "Gang of Four", and it turned out that I didn't understand it at all: I seemed to understand it when I read it, but then I forgot about it after a while. Maybe it's because I'm relatively "stupid" :)) Recently, I have some insights. "It's better to be happy alone than to be happy together", I would like to share it with you, and I hope you can give me some advice!
Why should we advocate "Design Pattern"? The fundamental reason is to reuse code and increase maintainability.
So how can we achieve code reuse? The OO world has several principles from its predecessors: the "Open Closed Principal" principle, the Liskov substitution principle, and the synthesis and reuse principle. Design patterns implement these principles to achieve code reuse and increase maintainability.
Open-Closed Principle
This principle was proposed by "Bertrand Meyer". The original text is: "Software entities should be open for extension, but closed for modification". That is to say, the module should be open for extension but closed for modification. Modules should try to be expanded without modifying the original ("original", referring to the original code) code. So how to expand? Let's look at the "factory pattern": Suppose there is a guy in Zhongguancun who sells pirated disks and pornographic films. We design a "CD sales management software" for him. We should first design a "CD" interface. As shown in the picture: [pre]______________|<>|| CD ||_____________|| Sell() || ||_____________|[/pre] And pirated discs and pornographic films are its subcategories. The boy manages these discs through "DiscFactory". The code is:
publicclassDiscFactory{ publicstatic光盘 getDisc(Stringname){ return(光盘)Class.forName(name).getInstance(); } }
Someone wants to buy a pirated disk, how to do it?
public class 小子{ public static void main(String【】 args){ CD d=DiscFactory.getDisc("Pirated Disc"); CD.Sell(); } }
If there is One day, this guy's conscience found out and he started selling genuine software. It doesn't matter, we just need to create another subcategory of "CD" called "genuine software". No need to modify the original structure and code. How about it? Open for extension, closed for modification. "Open-Closed Principle" The factory pattern expands specific products. Some projects may require more scalability. If you want to expand this "factory", it becomes the "abstract factory pattern".
Richter Substitution Principle
The Liskov substitution principle was proposed by "Barbara Liskov". If the parent class is called, it can be run if it is changed to a subclass. For example: CD d=new pirated disk(); d. sell(); If you want to change the "pirated disk" category to the "pornographic film" category, no problem, it can run completely. The Java compiler checks whether the program complies with the Liskov substitution principle. Do you still remember a principle of Java inheritance? The access rights of the override method of the subclass cannot be less than the access rights of the corresponding method of the parent class. For example, the access permission of the method "Sell" in "CD" is "public", then the "Sell" method in "Pirate Disc" and "Raw Film" cannot be protected or private, and the compilation will not pass. Why has to be this way? Think about it: if the "selling" method of "pirated disks" is private. Then the following code cannot be executed: CD d=new pirated disk(); d. sell(); It can be said that the Liskov substitution principle is a basis for inheritance and reuse.
Principle of synthesis and reuse
It means that inheritance should be used less and synthesis relationships should be used more. I once wrote a program like this: there are several classes that need to deal with the database, so I write a class for database operations, and then other classes that deal with the database inherit this. As a result, later, I modified a method of the database operation class, and all classes needed to be modified. "One move affects the whole body"! Object-oriented is to limit fluctuations to the smallest possible range.
In Java, you should try to program for Interface rather than implementation classes. This way, changing a subclass won't affect the code that calls its methods. Let each category have as little contact with others as possible, "Don't talk to strangers." In this way, if the city gate catches fire, the fish in the pond will not be harmed. Only when scalability and maintainability can be improved
After understanding these principles, and then looking at the design pattern, it is just about how to implement these principles on specific issues. Zhang Wuji learned Tai Chi, forgot all the moves, and defeated the "Two Elders Xuan Mi". It was said that he "had no moves in his mind". Design patterns can be described as tricks. If you first learn all the patterns, then forget all the patterns and do whatever you want, it can be called the highest state of OO. Haha, funny, funny! (JR)
Dependency Inversion Principle Abstraction should not depend on details, details should depend on
Dependency Inversion Principle
Program to the interface, not to the implementation. When passing parameters, or in combined aggregation relationships, try to reference higher-level classes. The main reason is that various concrete objects can be dynamically created when constructing objects. Of course, if some concrete classes are relatively stable, there is no need to make an abstract class as its parent class. This is superfluous. The interface isolation principle customizes services. Example, each
Interface Isolation Principle
A role, no more, no less, don’t do things you shouldn’t do, and do what you should do Abstract classes have to do everything. Abstract classes will not have instances
Abstract class
Classes are inherited by subclasses and generally contain common attributes and methods of this system. Note: In a good inheritance relationship, only leaf nodes should be concrete classes, and other nodes should be abstract classes, which means that concrete classes are not inherited. Put as much common code as possible into abstract classes. 7 Demeter's Law of Minimum Knowledge Principle. Don't talk to strangers.
Content covered by this design pattern tutorial manual
This design pattern tutorial covers the introduction of all design patterns, including Factory Pattern, Abstract Factory Pattern, Singleton Pattern (Singleton Pattern), Builder Pattern (Builder Pattern), Prototype Pattern (Prototype Pattern), etc.
Tips: Each chapter of this tutorial contains many Java examples, which will help you better learn and understand design patterns.
Latest chapter
Related courses
- Computer network knowledge collection 2022-09-30
- Boolean Education HTTP Protocol Video Tutorial 2022-04-14
- Boolean Educational Regular Expression Video Tutorial 2022-04-18
- Boolean Educational Design Pattern Video Tutorial 2022-04-21
- Overview of computer networks—basic knowledge that programmers must master 2021-11-22
- A must-have tutorial for programmers—detailed explanation of HTTP protocol 2021-11-19
- A one-hour comprehensive introduction to HTTP protocol—essential for web development 2021-11-26
- Master the basics of the Web in 90 minutes (network protocol | HTTP | Web server) 2021-12-10