Hello, I am the south orange, ten thousand method immortal door of the door, just from the kyushu world through the earth, because of the impact of space-time turbulence lead to my magic all lost, now have to pass this platform to the vast xiuzhen genius to borrow strength. Every “like” and “attention” from you will help me to come back to kyushu world. Watch for WX: Southern Orange RYC.
After I go back, we are all the elders of ten thousand method immortal door, I will give you countless days of material to treasure, everyone such as dragon, the whole people soar.
Wanweixian network as its name, the method in a space superimposed countless dimensions, the use of hyperlink technology, can be free in each dimension shuttle.
When Li Changgeng just entered, he appeared in a place that imitated the Gate of Ten thousand faxian. There were all kinds of colorful bubbles floating around, which reflected the silhouette of the small world inside. There were other disciples around him occasionally, and they hurried to other Spaces through the small bubbles.
“Look at the junior teacher standing here so long, not like a card, and look at your dress, should be a new comer?” A little girl dressed in Peking Opera stopped in front of Li Xiaogeng.
“Yes, what do you want?” Li Xiaogeng smiled and answered, compared with the people who hurried by here, he was antipired because he was dressed in ordinary clothes.
The other party smiled and pushed a packet to Li Xiaogeng: “It’s nothing. It’s your first time to enter the wan Fa Intranet, so you don’t know me. I am Zhou Mingrui, the chief disciple of this year’s Wanfa Semen gate, but I am commonly known as Klein. This packet contains some reference materials and search rules for the Wanfaxianmen Intranet, as well as some novice decorations, which can change their appearance by themselves.”
“Ah! How do you dress up with cloud violet?” Li Xiaogeng was severely shocked.
“You rarely surf the Internet.” Gram total again wu mouth smile: “teacher younger brother, I just zhou Mingrui oneself stay here to receive everybody’s artificial intelligence just, as to why dress up the appearance of cloud violet, however is this period of xp just.”
Li Xiaogeng and zhou Mingrui covered with the skin of the violets talked for a period of time, not long, there are new people into the Intranet, Li Xiaogeng will no longer stay, according to the guidance of Zhou Mingrui to the next space.
The destination this time, Wanfa Design Center.
Wanfa Design Center is one of the largest legware design centers in Kyushu, through the combination and optimization of 23 design modes, countless legware with various characteristics was born here, and even there are hundreds of working groups in the mixer school all year round to communicate with each other and learn from each other.
Of course, in the wan Fa Intranet, the main function of the design center or simulation and teaching.
“Do you want to know the meaning of life? Do you want to truly live? Come and buy the latest inborn calculator!”
“As an ordinary person, don’t you envy the way that the sword practitioners of Tiandao Jianzong ride the wind with their swords and wander between heaven and earth? Politeness pavilion new external jindan, build the base period can be used, the maximum output power up to 12MB, with the magic sword imperial Thunder true formula and sword 23, round you do a sword fairy dream.”
Just into the design center of the area, the oncoming advertising flow instantly appeared in Li Xiaogeng’s eyes, difficult to ignore these look very attractive information, Li Xiaogeng according to zhou Mingrui search rules to find what he wants to see.
Design patterns
Seven principles of design patterns
1. Open and close principle
At its core, the open-closed principle is open to expansion and closed to modification. When the program needs to be extended, it is not to modify the original code, but to extend the original code, to achieve a hot plug effect. So a word summary is: in order to make the program expansibility, easy to maintain and upgrade.
The open closed principle can be implemented by “abstracting constraints and encapsulating changes”, that is, defining a relatively stable abstraction layer for software entities through interfaces or abstract classes, while encapsulating the same variable elements in the same concrete implementation class.
2. Principle of single responsibility
The single responsibility principle states that a class should have only one cause for its change, not more than one, or the class should be split.
The single responsibility principle is the simplest and most difficult principle to apply, requiring the designer to discover the different responsibilities of a class, separate them, and encapsulate them into different classes or modules.
3. Richter’s substitution principle
Richter’s substitution principle mainly describes some principles about inheritance, that is, when inheritance should be used, when inheritance should not be used, and the underlying principles. Richter substitution is the basis of inheritance reuse, which reflects the relationship between base class and subclass, is a supplement to the open and closed principle, and is the specification of concrete steps to achieve abstraction.
In plain English, the Richter substitution principle says that a subclass can extend the functionality of its parent class, but cannot change the functionality of its parent class.
4. Rely on the inversion principle
The dependency inversion principle aims to reduce the coupling between classes through interface oriented programming. It is an important approach to realize the open and closed principle, which reduces the coupling between the client and the implementation module. The core idea is: program to the interface, not to the implementation.
4. Interface isolation principle
The interface isolation principle requires that we try to break up the bloated interface into smaller and more specific interfaces, so that the interface contains only the methods that the customer is interested in. There are no methods in each interface that subclasses cannot use but must implement; otherwise, the interface should be split. Using multiple isolated interfaces is better than using a single interface.
5. Demeter’s Rule
The definition of Demeter’s law is that the less a class knows about the classes it depends on, the better. No matter how complex the dependent class is, the logic should be encapsulated inside the method and made available externally through public methods. In this way, when the dependent class changes, the class will be minimally affected.
Another expression of Demeter’s rule is to correspond only with direct friends. Whenever there is a coupling between classes, it is called a friend relationship. Coupling is divided into dependency, association, aggregation, composition and so on. We call the classes that appear as member variables, method parameters, and method return values direct friends. Local variables, temporary variables are not direct friends. We require unfamiliar classes not to appear as local variables in a class.
6. Principle of composite reuse
The principle of composite reuse is also called the principle of combination/aggregation reuse. It requires that the combination or aggregation relationship should be used first, and the inheritance relationship should be considered second.
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.
“Is this your first visit to the design Center?” An ancient beast appeared in Li Xiaogeng’s side, bow: “I am the designer of the design center Wu Yanguang, shift as the new instructor of the Intranet, you can ask me what you don’t understand.”
Ten thousand method immortal door is worthy of ten thousand method immortal door, into the internal network after it is difficult to see and two yuan unrelated creatures.
Seeing the other party so polite, Li Xiaogeng also quickly returned the greeting: “Hello brother Wu, I want to design center to learn the design mode.”
“Very good ah, if it is to study, do not know whether there is a foundation before?”
“A little.”
“How do you classify design patterns?”
“This method is usually divided according to the mode is used to accomplish what work, this way can be divided into the creation mode, structure mode and behavior mode, according to the scope of use to divide the type can be divided into class mode and object mode two **
Second, the division of design mode
The essence of design pattern is the practical application of object-oriented design principles, and it is a full understanding of the encapsulation, inheritance and polymorphism of classes, as well as the association and combination of classes
The creation pattern focuses on “how to create objects” and its main feature is the separation of object creation and use. This reduces the coupling of the system, and the user does not need to focus on the details of object creation, which is done by the associated factory. Just like when we go to the mall to buy goods, we don’t need to know how they are made, because they are made by specialized manufacturers.
The structural pattern describes how classes or objects are composed to achieve functionality. It is mainly divided into class structure pattern and object structure pattern. The class structure pattern adopts inheritance mechanism to organize interfaces and classes, and the object structure pattern adopts combination or aggregation to combine objects.
Behavior mode is the abstraction of dividing responsibilities and algorithms among different objects, which is used to describe the complicated process control of the program at runtime, that is, to describe how multiple classes or objects cooperate to accomplish tasks that a single object cannot accomplish alone. It involves the assignment of responsibilities between algorithms and objects.
Class pattern: Used to deal with relationships between classes and subclasses, which are established by inheritance and are static and determined at compile time
Object pattern: Used to deal with relationships between objects, which can be implemented through composition or aggregation, that can change at run time and be more dynamic
Scope, purpose | Creation pattern | Structural mode | Behavioral pattern |
---|---|---|---|
Class model | The factory method | (Class) adapter | Template methods, interpreters |
Object pattern | Singleton prototype abstract factory builder | The broker (object) adapter Bridges the decorative appearance share element combination | Policy command responsibility Chain state observer mediator iterator visitor memo |
There are five creation modes:
- Singleton pattern: Only one instance of a class can be generated. This class provides a global access point for external access to the instance. The extension is the finite-multiple pattern.
- Prototype pattern: Take an object as a Prototype and clone it to create new instances that are similar to the Prototype.
- FactoryMethod pattern: defines an interface for creating products, and subclasses decide what products to produce.
- AbstractFactory pattern: provides an interface to create a family of products, each subclass of which can produce a series of related products.
- Builder pattern: Decompose a complex object into relatively simple parts, then create them separately according to different needs, and finally build the complex object.
Structural modes are divided into the following 7 types:
- Proxy mode: Provides a Proxy for an object to control access to that object. That is, a client indirectly accesses an object through a proxy to restrict, enhance, or modify some of its features.
- Adapter pattern: Converts the interface of one class into another interface that the customer expects, making classes that would otherwise not work together due to interface incompatibility work together.
- Bridge pattern: Separate the abstraction from the implementation so that they can vary independently. It is realized by using combinatorial relation instead of inheritance relation, thus reducing the coupling degree between abstraction and implementation of these two variable dimensions.
- Decorator pattern: Dynamically assign responsibility to an object, that is, add additional functionality to it.
- Facade pattern: Provides a consistent interface to multiple complex subsystems, making them more accessible.
- Flyweight pattern: Sharing techniques are used to efficiently support reuse of large numbers of fine-grained objects.
- Composite pattern: Groups objects into a tree-like hierarchy, giving users consistent access to individual and Composite objects.
Behavioral pattern is the largest type of design pattern, which includes the following 11 patterns:
- Template Method pattern: Defines the skeleton of an algorithm in an operation, deferring some steps of the algorithm to a subclass so that the subclass can redefine specific steps of the algorithm without changing the structure of the algorithm.
- Strategy pattern: A series of algorithms are defined and each algorithm is encapsulated so that they are interchangeable and the change of the algorithm does not affect the customers using the algorithm.
- Command pattern: Encapsulates a request as an object, separating the responsibility for making the request from the responsibility for executing the request.
- Chain of Responsibility pattern: Requests are passed from one object in the Chain to the next until the request is responded to. In this way, objects are decoupled.
- State mode: Allows an object to change its behavior when its internal State changes.
- The Observer pattern: There is a one-to-many relationship between objects. When one object changes, the change is notified to the other objects, thereby affecting the behavior of the other objects.
- Mediator mode: Define an intermediary object to simplify the interaction between the original objects, reduce the degree of coupling between the objects in the system, so that the original objects do not need to understand each other.
- The Iterator pattern: Provides a way to access a series of data in an aggregate object sequentially without exposing the internal representation of the aggregate object.
- Visitor pattern: Provides multiple access to each element in a collection without changing the collection elements, that is, multiple Visitor objects for each element.
- Memento pattern: Retrieves and saves the internal state of an object so that it can be restored later without breaking encapsulation.
- The Interpreter pattern: Provides the grammar of how to define a language and the method of interpreting language sentences, called the Interpreter.
“It seems that you have done some research.” Wu Yanguang said with a smile, “I don’t know what I want to learn today.”
“Real not: I am new to cloud temple disciple Li Xiaogeng, brother, you know, we will cloud temple soldier micro oligonucleotides, but it is too much, a magic weapon of what started a few years, built in the base period is not in the past, has been installed, nightfall can’t, because the low level, so you need to learn how to adapter pattern is compatible with the different properties of a magic weapon.”
Wu Yanguang’s mouth twitched slightly, and the trigeminal nerve at the temple jumped slightly. After taking a deep breath for several times, he slowly said, “Good teacher, I will tell you my understanding of the adapter mode.”
Adaptor mode
The adapter pattern transforms the interface of one class into another interface that the customer expects, making classes that would otherwise not work together due to interface incompatibations work together. The adapter pattern is divided into class structure pattern and object structure pattern. The coupling degree between the former class is higher than the latter, and the application is relatively less.
Advantages of the adapter pattern:
1. The client can transparently invoke the target interface through the adapter. 2, reuse the existing class, do not need to modify the original code and reuse the existing adapter class. 3. Decouple the target class from the adapter class to solve the problem of inconsistent interface between the target class and the adapter class.Copy the code
Disadvantages of the adapter pattern:
1. The process of writing adapters needs to be considered comprehensively in combination with business scenarios, which may increase the complexity of the system. 2, increase the difficulty of code reading, reduce code readability, too much use of adapters will make the system code become messy.Copy the code
In the actual work, sometimes there will be a company merger or acquisition of other companies (sure), at this time, will give other company code to receive, if you have the same similar module, often need to code to merge, adapter pattern makes originally because the interface is not compatible and can’t work with the class can work together. Or you are using a component provided by a third party, but the interface definition of the component is different from the required interface definition. Use the adapter pattern to solve this problem. Or the previously developed system has classes that meet the functional requirements of the new system, but their interfaces are inconsistent with those of the new system.
All of these are reasons to use the adapter pattern.
One more word: design patterns are the crystallization of previous experience, each design pattern solves a specific problem, using these design patterns is standing on the shoulders of predecessors. Design patterns are more about learning from previous experiences than using for the sake of using or showing off for the sake of showing off.
The main roles of the adapter pattern:
Target interface: The interface expected by the current system business. It can be an abstract class or interface. Adapter class: This is a component interface in an existing component library that is accessed and adapted. Adapter class: It is a converter that converts an adapter interface into a target interface by inheriting or referencing an adapter's object, allowing the client to query the adapter in the format of the target interface.Copy the code
Fourth, class adapter pattern implementation
1. Target interface
Public void sellSmoke(); public void sellSmoke(); }Copy the code
2. Adaptor class
Public void companyGD(){system.out.println (" GuangdongSmoke "); public void companyGD(){system.out.println (" GuangdongSmoke "); } @Override public void sellSmoke() { this.companyGD(); }} public void companyGZ(){system.out.println (" companyhousmoke "); }}Copy the code
3. Adapter classes
Public class Adapter extends GuiZhouSmoke implements Smoke {/** * Override public void sellSmoke() {super.panygz (); }}Copy the code
4. Test classes
Public static void main(String[] args) {Smoke gd =new GuangdongSmoke(); gd.sellSmoke(); Smoke gz =new Adapter(); gz.sellSmoke(); // Tobacco monopoly in Guizhou Province}Copy the code
The Adapter implemented above is called a class Adapter, because the Adapter class inherits both GuiZhouSmoke (adapted class) and Smoke interface. In the test class, we can select and create any subclass that meets the requirements to implement specific functions.
Of course, you can refer to the SpringMvc adapter in real development.
Spring defines an adaptation interface so that each Controller has a corresponding adapter implementation class that performs the corresponding methods instead of the Controller. When you extend Controller, you only need to add an adapter class to complete the extension of SpringMVC
Realization of object adapter pattern
Another adapter pattern is the object adapter, which uses direct association, or delegation, rather than inheritance and re-implementation.
1. Target interface
Public void sellSmoke(); public void sellSmoke(); }Copy the code
2. Adaptor class
Public void companyGD(){system.out.println (" GuangdongSmoke "); public void companyGD(){system.out.println (" GuangdongSmoke "); } @Override public void sellSmoke() { this.companyGD(); }} public void companyGZ(){system.out.println (" companyhousmoke "); }}Copy the code
3. Adapter classes
This time the adapter class is directly associated with the adapted class and implements the standard interface
public class Adapter implements Smoke { private GuiZhouSmoke guiZhouSmoke; public Adapter(GuiZhouSmoke guiZhouSmoke) { this.guiZhouSmoke = guiZhouSmoke; } /** * adaptor class, inheriting the adaptor class, Implement a standard interface * is equivalent to through intermediate code will guizhou tobacco information access guangzhou * / @ Override public void sellSmoke () {this.guiZhouSmoke.com panyGZ (); }}Copy the code
4. Test classes
Public static void main(String[] args) {Smoke gd =new GuangdongSmoke(); gd.sellSmoke(); GuiZhouSmoke =new GuiZhouSmoke(); Smoke gz =new Adapter(guiZhouSmoke); gz.sellSmoke(); // Tobacco monopoly in Guizhou Province}Copy the code
As can be seen from the DIAGRAMS of IEDA, as long as the Adapter has an object of the adapted class, it delegates specific special functions to this object. Using the object Adapter pattern, the Adapter class can be adapted to multiple different Adaptee classes based on the incoming Adaptee object. Of course, we can extract an interface or abstract class for multiple Adaptee classes. This makes the object adapter pattern a little more flexible.
In Spring’s AOP, the proxyed class is enhanced by using Advice. Spring implements this AOP functionality using the proxy pattern (1) JDK dynamic proxies. 2. CGLib bytecode generation technology agent. The class method level section enhancement, that is, the generation of proxy class proxy class, and in front of the proxy class method, set the interceptor, through the implementation of the interceptor content enhanced the function of the proxy method, the realization of section-oriented programming.
Advice types include BeforeAdvice, AfterReturningAdvice, and ThrowSadvice. Each type of Advice (inform) have corresponding interceptors, MethodBeforeAdviceInterceptor, AfterReturningAdviceInterceptor, ThrowsAdviceInterceptor. Spring needs to wrap each Advice into a corresponding interceptor type and return it to the container, so you need to use the adapter pattern to transform Advice.
Application of adapter pattern
The adapter pattern is mainly used when you want to reuse some existing classes, but the interface does not match the requirements of the reuse environment. For example, it has practical value in applications where you need to reuse some functionality from earlier code. There are three applicable scenarios:
- 1. The interface of the existing class does not meet our requirements.
- 2. Create a reusable class that can work with unrelated or unpredictable classes (classes whose interfaces may not be compatible).
- 3. Use existing subclasses without subclassing each one to match their interfaces.
The adapter pattern encapsulates the existing system and provides a more convenient access interface for the existing system. The adapter mode is designed after the fact. No new interface is introduced, but an interface is indirectly converted to another interface through adaptation.
Li Xiaogeng heard the explanation, from the storage ring took out a lot of method (real-time calculus), a little construction, then form in the Dan tian into a interface, the original dim method suddenly changed the time overflow.
“But remember, after leaving the Intranet, do not directly start to build the interface, the access device still need to be reviewed by experts, to prevent some conflicts and even introduce some fatal flaws.”
“So, thank you brother, I will give you five star praise, but we have a professional expert temple, this point you rest assured.”
“You’re welcome, big dog.”