GRASP (Responsibility Assignment principle)

Source: Internet
Author: User

To learn the design pattern, we must first know some basic knowledge. The design pattern is an efficient and flexible way to use classes and objects. That is to say, only when there are classes and objects can we have a place to use the design model. Otherwise, everything is empty talk, so what about classes and objects? In this case, the GRASP model, which is more important than the 23 design modes, is now available. Hey hey, this is the boss!

GRASP (General Responsibility Assignment Software patterns) is called "General Responsibility Assignment software model" in Chinese. Grasp consists of nine modes, which describe the basic principles of Object Design and Responsibility Assignment. That is to say, how to abstract the business functions of the real world into objects, how to determine the number of objects in a system, and what responsibilities each object includes, the GRASP mode provides the most basic guiding principles. Beginners should master and understand these principles as soon as possible, because this is the basis for designing an object-oriented system.It can be said that,GRASPIs the basis for learning to use design patterns.

1.Information expert (Information expert)

The information expert model is the most basic principle of object-oriented design. It is the most commonly used principle that should be integrated with our ideas. That is to say, when we design an object (class), if a class has all the information required to complete a specific responsibility, this responsibility should be assigned to this class for implementation. At this time, this class is the information expert relative to this responsibility.

For example:The shopping cart (shopcar) in a common online store must appear only once in the shopping cart. To buy the same item, you only need to update the quantity of the item. For example:

(Skuid) is used to uniquely distinguish commodities, and commodity numbers are unique in the commodity category. Therefore, according to the information expert model, you should put the methods for comparing commodities in the commodity category.

 

2.Creator (Creator)

In practice, Class A should be used to create Class B when any of the following conditions are met. At this time, a is the creator of Class B:

A.A is the aggregation of B.

B.A is the container of B.

C.A holds the information of initializing B (data)

D.Instance a records B

E.A frequently uses B

If one class creates another class, the two classes are coupled and can be said to have dependencies. There is no error in dependency or coupling, but the problems they bring about are that they will generate a chain reaction in future maintenance, and the necessary coupling cannot be escaped, what we can do is to correctly create Coupling Relationships and do not randomly establish dependencies between classes. What should we do? It is necessary to abide by the basic principles stipulated by the Creator mode. If the above conditions are not met, a cannot be used to create B.

For example: Because order is the container of a commodity (SKU), the order should be used to create a commodity. For example:

 

3.Low coupling (Low Coupling)

The low coupling mode means we need to minimize the connections between classes.

Its role is very important:

A.Low coupling reduces the impact on other classes due to changes in one class.

B.Low coupling makes the class easier to understand, because the class will become simpler and more cohesive.

The following situations may cause coupling between Class A and Class B:

A.A is the property of B.

B.Method for a to call B's instance

C.B is referenced in method A. For example, B is the return value or parameter of method.

D.A is a subclass of B, or a implements B

There are also some basic principles for low coupling:

A.Don't talk to strangers principles:

That is to say, do not make unnecessary connections between two objects that do not need to communicate. If the connection is established, problems may occur. If it is not connected, it will be a hundred times!

B.If a is connected to B, and B is not assigned the responsibility of A (in violation of the information expert model), B is assigned the responsibility of B.

C.Internal classes of two different modules cannot be directly connected; otherwise, you will be rewarded! Hey!

For example: In the example of the Creator model, another shipping person is required to check the goods (SKU) on the order and calculate the total price of the goods, however, because the coupling between orders and commodities already exists, assigning this responsibility to orders is more appropriate, which can reduce coupling and reduce system complexity. For example:

The totalprice () method is used to calculate the total price without adding unnecessary coupling.

 

4.High Cohesion (High Cohesion)

High Cohesion means assigning cohesion responsibilities to classes as much as possible. It can also be said to be functional cohesion responsibilities. That is, the function is closely related to the responsibilities should be put in a class, and the limited functions should be completed together, that is, high internal aggregation. This is more conducive to class understanding and reuse, and also facilitates class maintenance.

High cohesion can also be said to be an isolation. The human body is composed of many independent cells. The building consists of many bricks, steel bars, and concrete. Each part (class) each part has its own independent responsibilities and features. If a problem occurs in each part, it will not affect other parts, because highly cohesive objects are isolated.

For example: An order Data Access class (orderdao) can be saved as an Excel mode or saved to a database. Therefore, different responsibilities are best achieved by different classes, this is the design of high cohesion, such:

If the EXCEL function is incorrect, you can check the orderdaoexcel class. This also makes the system more modular and easier to divide tasks, for example, the two classes can be assigned different persons for development at the same time, which also improves the team collaboration and development progress.

 

5.Controller (Controller)

The responsibility for receiving and processing system events should generally be assigned to a class that can represent the entire system, such classes are usually named "XX processor", "XX coordinator", or "XX session ".

The following principles apply to the Controller class:

A.The receiving and processing of system events is usually replaced by an advanced class.

B.A sub-system has many controller classes to process different transactions respectively.

For more details about this mode, refer 《UMLAnd Mode Applications16Chapter.

6.Polymorphism (Polymorphism)

Polymorphism here is the same as "polymorphism", one of the three basic features of OO.

For example: We want to design a drawing.ProgramTo support drawing different types of images, we define an abstract class shape, rectangle and circle to inherit this abstract class and override them) the draw () method in the shape class, so that we can use the same interface (shape abstract class) to draw different images, such:

(Diamond) class does not have any impact on the entire system structure. You only need to add a class that inherits the shape.

 

7.Pure fabrication (Pure fiction)

The pure fiction here is similar to the pure fiction function we often call. High Cohesion and low coupling are the ultimate goal of system design, but cohesion and coupling are always contradictory. High Cohesion thinks that this splits more classes, but objects need to collaborate to complete the task, which in turn leads to high coupling. How can we solve this contradiction? In this case, we need to use a purely fictitious class to coordinate cohesion and coupling, which can solve the above problem to a certain extent.

For example: In the example of the above multi-state mode, if our plotting program needs to support different systems, the drawing function also needs different implementation methods because the API structure of different systems is different, so how should we design it more appropriately? For example:

Abstractshape, no matter which system can draw images through the abstractshape class, we do not reduce the original cohesion or increase too many coupling, it can be said that the fish and the bear's paw have both. Hahaha!

 

8.Indirection (Indirect)

As the name implies, "indirect" means that this task cannot be handled directly, and you need to make a detour. The benefit of turning around is that objects that are directly connected together are isolated from each other, and one change will not affect the other. Just as I said in the previous low coupling mode, "Internal classes of two different modules cannot be directly connected", but we can indirectly connect two different modules through intermediate classes, in this way, there is still no coupling/dependency between the two modules.

9.Protected variations (Protected changes)

Locate unstable changes in advance and encapsulate them with a unified interface. If future changes occur, you can use the interface to expand new functions without modifying the original implementation. This mode can also be understood as the OCP principle, that is to say, a software entity should be responsible for extension development, and the modification should be disabled. When designing a module, make sure that the module can be expanded without being modified. The advantage of doing so is to provide new responsibilities to the system through expansion to meet new requirements without changing the original functions of the system. The OCP principles will be discussed separately later.

Here we can see that the pure virtual libraries are added.

This design is more in line with the principles of high cohesion and low coupling, although we later added a diamond

Here we put two different data storage functions in two classes for implementation, so that if you save them

Here we add

This is because the order is the container of the product and only the information of the initial product is held by the order. Therefore, this coupling relationship is correct and cannot be avoided. Therefore, the order is used to create the product.

To solve this problem, we need to weigh whether the same methods of products need to be put into the class for implementation? According to the product ID

 

We live in a world full of Rules. Under the complex and changing appearance, everything is governed by the eternal truth and operates regularly. The same is true for patterns. Whatever the patterns, there are some "eternal truths" hidden behind them. This truth is the design principle. I remember when I attended an architect training at Microsoft and talked about the design model, someone asked the teacher a question: "What is more important than the design model ?", The teacher is a developer with many years of practical experience. He did not hesitate to say, "What is more important than model is principle ". I often think of this sentence as a great answer. Indeed, what is more important than principles? Just like people's world outlook and outlook on life, it is the root of all your actions. For design patterns, why does this pattern solve this problem like this, and for other models, they all follow the principle of eternal design.It can be said that the design principle is the soul of the design model.

I have not discussed the design principles in depth yet. I suggest you take a look.Agile Software Development-principles, models and practices:

1.Single Responsibility Principle(SRP)

"For a class, there should be only one reason for its change ." That is to say, do not put different responsibilities for different reasons of change together, because different changes will affect irrelevant responsibilities. In other words, you don't need to worry about things you shouldn't care about. You can manage your own things, and your own things hurt others. (Of course, we have two different things to do here, and we advocate "yes" and "yes !)

For example: For the design in reference, the graphic computing program only uses the square area () method and never uses the draw () method, but is associated with the draw method. This violates the single principle. If the draw () method changes due to the graphic plotting program in the future, it will affect the graphic computing program that is unrelated to it.

So what should we do? For example, assign different responsibilities to different classes so that the responsibilities of a single class are as single as possible, and changes are isolated so that they will not affect each other.

 

 

From: http://www.cnblogs.com/sevenyuan/archive/2010/03/05/1678730.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.