Understanding Object-oriented Thinking

Source: Internet
Author: User
Object-oriented thinking:
Object-Oriented Analysis and Design of software systems around objects and classes.
Object-Oriented Analysis:
The main task of object-oriented analysis is to build an accurate, complete, and consistent system model based on the needs of users. In the process of object-oriented analysis
The group obtains an idealized system model by analyzing the functional requirements of the software. The model focuses more on describing the problems solved by our needs.
Is the analysis model.
Differences between object-oriented analysis and object-oriented design:
1. In terms of emphasis, object-oriented analysis focuses on understanding the problem and describing what the software is doing, while object-oriented design focuses on understanding the solution and describing how the software works.
2. object-oriented analysis generally only considers the ideal design and does not care about the technical and implementation details. The object-oriented design is more specific, more detailed, and closer to the actual code design scheme.
3. In terms of the description of design results, the analysis stage focuses on describing the behavior of objects, and the design stage focuses on describing the attributes and methods of objects.
4. object-oriented analysis only focuses on functional requirements, while object-oriented design focuses on both functional requirements and non-functional requirements.
5. the system model generated by Object-Oriented Analysis is usually relatively small, while the system model generated by object-oriented design is large and complete and detailed.
Case-driven object-oriented analysis:
The process of object-oriented analysis includes:
1. Extract object objects and object classes from use cases.
The entity object extraction method extracts entity objects based on the nouns and noun phrases in the case description. The original nouns and Noun Phrases must be filtered.
After an object is obtained, the object class is summarized and abstracted.
2. Extract attributes
3. Relationship Extraction
4. Add a boundary class
5. Add a control class
6. Draw a class chart
7. Draw a Sequence Chart
8. Prepare a glossary

If you have the idea to fly, the lack of flexibility is like a car without wheels, and it is difficult to fly. In order to better understand the design concept, we can use a concise example to describe the Ood, design mode and reconstruction. Pass
The following code details the idea of object-oriented design.
I. The traditional procedural design concept assumes that we need to design a Media Player (only from the software design perspective, not involving hardware ). Currently, this media player only supports audio files MP3 and WAV. Structured settings
The player code is as follows:

 

Object-Oriented Design ( OOD ) Thought ( C # )If you have the idea to fly, the lack of flexibility is like a car without wheels, and it is difficult to fly. In order to better understand the design concept, we can use a concise example to describe the Ood, design mode and reconstruction. The following code details the idea of object-oriented design. I. Traditional Procedural Design IdeasSuppose we want to design a Media Player (only from the software design point of view, does not involve hardware ). Currently, this media player only supports audio files MP3 and WAV. According to the structured design idea, the code of the player is as follows: public class mediaplayer {private void playmp3 () {MessageBox. show ("Play the MP3 file. ");} private void playwav () {MessageBox. show ("Play the wav file. ");} public void play (string audiotype) {Switch (audiotype. tolower () {Case ("MP3"): playmp3 (); break; Case ("WAV"): playwav (); break ;}}} from the traditional procedural design ideas, this is a piece of practical and concise code. If the customer asks that the player not only play MP3 and wav files, but also play other audio files, such as WMA and MP4, for this reason, we need to constantly add the corresponding playback method and modify the condition statement. The limit statement is long enough. If the customer feels that this media player has too few features, they can only hear it and cannot see it. It is too simple. If you are listening
It is better to see the elegant and handsome dance of the artist while enjoying the beautiful music. From the perspective of code design, they want media players to support video files. Maybe you will think that there will be no more video
Code, yes. When adding the video media playing method, you can modify the condition judgment statement. If there are other statements, you can add and modify them as well. At this point, you may propose that if you do not modify or rarely modify the original code
How nice it is to add other functions! In this way, the original software design structure seems a bit problematic. In fact, as the number of features increases, you will find that
The design is very bad, because it does not provide a minimum extension for future demand changes. In order to meet the overwhelming demand for changes, you have to tirelessly modify the original code to adapt to changes in requirements.
When you modify the code, too many code dependencies make a mess. Ii. object-oriented design ideasTake the design of a media player as an example. The design requirements are the same. Without visiting us, we will change our design ideas and use the object-oriented design idea (OOD) to learn how to do it! According to the idea of OOD, we should regard MP3 and WAV as two independent objects respectively. The Code is designed as follows: public class MP3 {public void play () {MessageBox. show ("Play the MP3 file. ") ;}} public class WAV {public void play () {MessageBox. show ("Play the wav file. ") ;}} public class mediaplayer {Switch (audiotype. tolower () {Case ("MP3"): MP3 M = new MP3 (); M. play (); break; Case ("WAV"): wav w = new WAV (); W. play (); break ;}}
Now let's refactor the code and build a unified play () method. (In the later design, you will find how important it is to change the name !) Modify the mediaplayer code of the media playback class. If
Such a design code does not change much in nature. It is only an alternative to the original procedural design idea and does not hit the key. Also, there is no flexibility or scalability. 2.1 Application of One-Way dispatching technology ( This is implemented by class polymorphism)We do not want to access this idea: since MP3 and WAV are both audio files that share the same characteristics, we should establish a common audiomedia parent class. Public class audiomedia {public void play () {MessageBox. show ("Play the audiomedia file. ") ;}} now we have introduced the idea of inheritance. OOD is a little prototype (not to say that we have the idea of inheritance. Here we just talk about it from the perspective of inheritance, of course, from other perspectives, such as synthesis and aggregation, the idea of Ood can also be well reflected ). In fact, in real life, our player can only play certain types of audio files, such as MP3. Therefore, this audiomedia class can only be an abstract concept of audio media, there is no actual use case. In the Ood design, this class will never be instantiated. Therefore, we should change it to an abstract class, as follows: public abstract class audiomedia {public abstract void play ();} public class MP3: audiomedia {public override void play () {MessageBox. show ("Play the MP3 file. ") ;}} public class WAV: audiomedia {public override void play () {MessageBox. show ("Play the wav file. ") ;}} public class mediaplayer {// One-Way assignment of the task as needed public void play (audiomedia media) {media. play () ;}here, we use the one-way allocation Technology The idea of OOD is further embodied. The current design satisfies the hierarchical relationship between classes, ensures the minimum principle of classes, and also reflects the object-oriented design principles (open-closed principle and the Li's replacement principle) more conducive to expansion. (You will find out how necessary the change of the play method name is ). If you have added the playback of WMA, MP4, and other audio files, you only need to design the WMA and MP4 classes and inherit the audiomedia class. Then, rewrite the play method in the corresponding subclass, the play method of mediaplayer objects does not need to be changed at all. To enable the media player to support video files, you must design a category for Video Media. Because there are many differences between video files and audio files, it is impossible to inherit audio from videos. Assume that our player supports videos in the RM and MPEG formats. The video class code is as follows: public abstract class videomedia {public abstract void play ();} public class RM: videomedia {public override void play () {MessageBox. show ("Play the RM file. ") ;}} public class MPEG: videomedia {public override void play () {MessageBox. show ("Play the mpeg file. ") ;}} the design is still a bit bad, so that the original mediaplayer class cannot be used. Because the RM file of the video you want to play is not a subclass of audio media.
However, we can think like this: both audio and video media are media, and there are many similar functions, such as playing, pausing, and stopping, therefore, we abstract the concept of "Media" as an interface.
(Although abstract classes can also be used, only single inheritance of classes is supported in C #, but C # supports multi-inheritance of interfaces ). According to the interface definition, You can implement the same interface for a series of objects with the same function. Let
Both the audio and video media classes inherit the media interface. The Code is as follows: public interface imedia {void play ();} public abstract class audiomedia: imedia {public abstract void play ();} public abstract class videomedia: imedia {public abstract void play ();} and then change the mediaplayer class code: public class mediaplayer {public void play (imedia media) {media. play () ;}} now it seems that the program has great flexibility and scalability. To sum up, from the evolution of the mediaplayer class, we can conclude that when calling the attributes and methods of class objects, we should avoid using specific class objects as passing parameters, instead, it is necessary to pass its abstract object, which is better to pass the interface and completely remove the actual call and specific object. This can reflect the flexibility and scalability of software engineering. It seems perfect now, but we ignore the fact that mediaplayer callers. Conditional statements are still required. For example, in the client code, you can select the cbbmediatype combo box option to decide whether to play the audio media or video media, and then click play. Public void btnplay_click (Object sender, eventargs e) {imedia media = NULL; Switch (cbbmediatype. selectitem. tostring (). tolower () {Case ("MP3"): Media = new MP3 (); break; // other types; Case ("RM "): media = new RM (); break; // other types;} mediaplayer player = new mediaplayer (); player. play (media );} 2.2 Application of design mode, external condition and reflection technologyAs demand increases, programs will become more and more complex. At this time, we should adjust the design idea and fully consider the code reconstruction and the application of the design pattern. Finally, when the design becomes more perfect, you will find that, even if the demand increases, you can be refreshed without worrying about code design. To achieve three main objectives of Software Engineering: reusability, flexibility, and scalability. We do not use the design mode, external conditions, and reflection. The factory mode ensures code flexibility by calling different objects (that is, dynamic calls) as needed. Although there are two different types of media audiomedia and videomedia (more in the future), they all implement the imedia interface at the same time, so we can regard it as a product. The media factory interface is as follows: public interface imediafactory {imedia createmedia ();} and then build a factory for the specific media file object, and uniformly implement the media factory interface: public class mp3factory: imediafactory {public imedia createmedia () {return new MP3 () ;}}// other factories; public class rmfactory: imediafactory {public imedia createmedia () {return New RM () ;}// other factories; if you write it here, some people may ask why they do not directly give audiomedia and videomedia
How about building a factory? It's easy, because there are different types of derivation in audiomedia and videomedia. If you build a factory for them
In the createmedia () method, condition-based judgment statements are still used. The Code lacks flexibility and is not scalable. Another problem is that it is really necessary to implement two abstractions: audiomedia and videomedia.
Class? Isn't it easier for its subclass to directly implement interfaces? The requirements mentioned in this article can be implemented. However, it is not ruled out that audiomedia and videomedia will have other differences, such
Audio files also need interfaces for sound cards, while video files also need interfaces for graphics cards. If you want MP3, WAV, RM, and MPEG to directly implement the imedia interface
Audiomedia and videomedia are also unreasonable in terms of design to meet other needs. Now the client code has changed a little: Public void btnplay_click (Object sender, eventargs e) {imediafactory factory = NULL; Switch (cbbmediatype. selectitem. tostring (). tolower () {// audio media case ("MP3"): factory = new mp3factory (); break; // Video Media case ("RM "): factory = new rmfactory (); break; // other types are omitted;} mediaplayer player = new mediaplayer (); player. play (factory. createmedia ();} Here, let's look back at the mediaplayer class. This class implements the play method for different objects based on different passing parameters through one-way allocation. This class Object runs well without the factory mode. As a class library or component designer, he provides a good interface for the client program to call. After using the factory mode, it seems that the mediaplayer class is redundant. Therefore, we should remember that refactoring is not just about adding new content to the original code. When we find unnecessary designs, we also need to delete the redundant code decisively. The modified code is as follows: public void btnplay_click (Object sender, eventargs e) {imediafactory factory = NULL; Switch (cbbmediatype. selectitem. tostring (). tolower () {Case ("MP3"): factory = new mp3factory (); break; // other types are omitted; Case ("RM "): factory = new rmfactory (); break; // other types are omitted;} imedia media = factory. createmedia (); media. play () ;}if you haven't realized the benefits of the imedia interface at the beginning, you should have understood it here. We are at the factory
This interface is used in the client program. What are the benefits of using interfaces? That is, your main program can be compiled without a specific service class. Therefore,
Even if you add new services, your client programs do not need to be changed. However, writing client code is not ideal and flexible enough. When determining which factory to create, you still need to determine the conditions. Now it seems that if the performer is not completely separated from the specific class, once the business of the specific class is changed, such as adding a new factory class, the client program code still needs to be changed. We can achieve client flexibility through reflection technology and external conditions. Conditional external implementation, that is, through the Application configuration file. We can put the type information of each media file class in the configuration file, and then select to create a specific object based on the configuration file. In addition, this method of object creation will be completed using reflection technology. First, create a configuration file: <appsettings> <add key = "MP3" value = "medialibrary. mp3factory "/> <add key =" WAV "value =" medialibrary. wavfactory "/> <add key =" RM "value =" medialibrary. rmfactory "/> <add key =" MPEG "value =" medialibrary. mpegfactory "/> </appsettings> then, in the client program code, customize an initialization method such as initmediatype () to read all the key values of the configuration file, fill in the cbbmediatype combo box control: Private void initmediatype () {cbbmediatype. items. clear (); foreach (string key in Configurationsettings. appsettings. allkeys) {cbbmediatype. item. add (key);} cbbmediatype. selectedindex = 0;} Finally, change the play button of the client program and click the event: Public void btnplay_click (Object sender, eventargs e) {string mediatype = cbbmediatype. selectitem. tostring (). tolower (); string factorydllname = configurationsettings. appsettings [mediatype]. tostring (); // medialibray is the referenced media file and factory assembly; imediafactory factory = (imediafacto Ry) activator. createinstance ("medialibrary", factorydllname ). unwrap (); imedia media = factory. createmedia (); media. play () ;}this demonstrates three major objectives of Software Engineering: reusability, flexibility, and scalability. Imagine if we want to add a media file playing function, such as an AVI file. Then, we only need
To create the AVI class in the business program and inherit from the videomedia class. Create the avifacloud class in the factory business and implement the imediafactory interface. False
If the new factory type is medialiabrary. avifacloud, add the following line in the configuration file: <add key = "Avi" value = "medialiabrary. avifacloud"/>. What about the client program? The program can run freely without any changes or re-compilation! Another: After the release of this article, an enthusiastic friend suggested that if the UML diagram is provided, it would be more perfect. Thank you for reminding me. The UML diagram is as follows: C # Object-Oriented Analysis comments 0Click to enter the Forum

Object-Oriented Analysis is a problem definition stage in software development. Its goal is to clearly and accurately define the problem field. Traditional system analysis generates a set of process-oriented documents that define the functions of the target system. object-oriented analysis generates a comprehensive document describing the basic features of the system functions and problem fields.

Principles

The main principles of object-oriented analysis are as follows.

1. Abstraction

Dropping individual and non-essential features from many things and extracting common and essential features is called abstraction. Abstraction is an essential means to form concepts.

Abstract principles have two meanings: first, although things in the problem domain are complex, analysts do not need to understand and describe everything about them, you only need to analyze and study the things related to the system goals and their essential features. Second, abstract concepts of a batch of things are obtained by extracting the common features of individual things from their differences in details.

Abstract is the most widely used principle in object-oriented methods. Abstract principles include process abstraction and data abstraction. Process abstraction refers to the user of any operation sequence that completes the function.
You can regard it as a single entity, although it may actually be completed by a series of lower-level operations. Data abstraction refers to defining the data type based on the operations applied to the data, and limiting the data value only
These operations can be used for modification and observation. Data abstraction is the core principle of object-oriented analysis. It combines data (attributes) and Operations (services) into an inseparable System Unit (object ).
You need to know what it does, instead of how it does it.

2. Encapsulation

Encapsulation is to combine object attributes and services into an inseparable System Unit and conceal the internal details of objects as much as possible.

3. Inheritance

The object of a special class has all the attributes and services of its general class. It is called the inheritance of a special class to the general class.

In object-oriented analysis, the inheritance principle is applied to every general-special structure formed by general classes and special classes, the owner that shares the object instance of a general class and all object instances of a special class
And services, which are explicitly defined in the general class at one time. In a special class, we do not repeatedly define what is already defined in a general class, but in terms of semantics, a special class automatically and implicitly owns its general class (and
All attributes and services defined in the upper-level general class. The advantage of the inheritance principle is that the system model is concise and clear.

4. Category

Objects with the same attributes and services are divided into one class, and classes are used as abstract descriptions of these objects. The classification principle is actually a manifestation of the abstract principle applied to object description.

5. Aggregation

The principle of aggregation is to regard a complex thing as the Assembly body of some simple things, so as to simplify the description of complicated things.

6. Join

Association is a way of thinking that humans often use when thinking about problems: think of another thing through one thing. The reason for association is that there are some relationships between things.

7. Message Communication

This principle requires that objects can only communicate through messages, rather than directly accessing internal properties of objects outside the objects. Message-based communication is caused by encapsulation principles. In OOA, a message connection is required to indicate the dynamic relationship between objects.

8. Granularity Control

Generally speaking, when faced with a complex problem domain, it is impossible for people to view the whole situation at the same time, and to understand the problem. Therefore, you need to control your own field of view: Pay attention to its major components when considering the global situation, and do not take details of each part for the time being; when considering the details of a part, the rest of the part is temporarily removed. This is the granularity control principle.

9. Behavior Analysis

The behavior of things in the real world is complex. Various behaviors in the problem domain composed of a large number of things are often mutually dependent and intertwined.

Phase

The object-oriented analysis process can be divided into two stages: problem domain analysis and application analysis.

Problem domain analysis is a basic component of software development. It aims to enable developers to understand the structure of the problem domain and establish a general system implementation environment. The problem domain analysis provides a set of abstract concepts (from the high-level
To indicate the problem domain knowledge, often beyond the scope of the current application) as a reference for the development of specific system requirements. Problem domain analysis is actually a learning process. Software developers should try to understand at this stage
In the current system, application-related knowledge should be opened up, and the scope of consideration should be relaxed to identify application-related concepts as much as possible. The boundaries of problem domain analysis may be vague. With extensive knowledge in problem fields
And the specific application, you can enter the State faster, master the core knowledge of the application. In addition, when users change their requirements for the target system, extensive analysis can help us predict what aspects of the target system will
Which changes have occurred. Usually conduct group analysis. The group members can include field experts and analysts. During the analysis, the basic concepts (objects, classes, methods, relationships, etc.) of the system should be identified and the problem identification should be conducted.
And integrate these concepts into the problematic domain model. The model of the problem domain must contain the relationship between concepts and all information about each concept. The concepts identified should be based on the information content.
Organically integrated into the comprehensive view of the problem field.

Application analysis is based on the problem domain model established during problem domain analysis. During application analysis, the problem domain model is used in the current specific application. First, the user
Information to make trade-offs between problem domains, and use user requirements as restrictions to reduce the amount of information in the problem domains. Therefore, the field of view of problem analysis directly affects the amount of information retained by application analysis. Average
For example, the models generated in the problem domain analysis stage do not need to be expressed in programming languages, while the impact conditions generated in the application analysis stage need to be expressed in a programming language. Model Recognition requirements can be tailored
One application can also target multiple applications. We usually focus on two aspects: application view and Class View. In the Class View, the attributes and operations of each class must be refined and mutual actions between classes must be expressed.
Relationship.

Target

Coad and Yourdon believe that object-oriented analysis should mainly consider objects related to specific applications and the relationship between structures and interactions between objects. In object-oriented analysis, an analysis model is required to describe the functions of the system.

Object-Oriented Analysis requires the following two tasks:

-Formally describe the application problems faced, and ultimately become the basic object of the software system, as well as the rules and constraints that the system must follow and are determined by the application environment.

-Explicitly specify how the objects that constitute the system work together and complete the specified functions.

The system model created through object-oriented analysis is conceptual and therefore called a conceptual model. A conceptual model consists of a group of related classes. Object-Oriented Analysis can build a system model through top-down decomposition, or start from the defined classes to build new classes. The construction and review of a conceptual model consists of the following five layers:

-Class and object Layer

-Attribute Layer

-Service Layer

-Structural layer

-Topic Layer

These five layers are not the layers of the software system, but the layers of the analysis process. It can also be said that the problem is different. Each layer of work adds an integral part to the System Specification Description. When all the five layers are completed, the task of object-oriented analysis is completed.

In practice, the objective of object-oriented analysis is to obtain functional models, object models, and dynamic models of the problem domain, and express them with the corresponding UML diagram.

Procedure

Object-Oriented Analysis is usually performed according to the following steps:

(1) identify objects and classes. The basic classes and objects of the entire application can be gradually determined from the application field. This step needs to analyze the responsibility of the target system in the field, investigate the system environment, and then determine the classes and objects that are useful to the system.

(2) identify structure. There are two typical structures: general-special structure and general-part structure. General-special structure indicates that a general class is a base class, and a special class is a derived class. For example, cars are cars and
The basis class of the truck, which is a general-special structure. Partial structure indicates aggregation, and members of different classes are aggregated into new classes. For example, wheels, car bodies, and chassis are all part of a car.
Function components are aggregated into the overall automobile.

(3) Identify attributes. The information saved by the object is called its attributes. Class attribute description status information. In an instance of the class, the attribute value indicates the status value of the object. You need to find the object in the object
Mark the required attributes in the system, arrange the attributes in the appropriate location, locate the instance connection, and then check. The name and description of each attribute should be given, and special restrictions (such as read-only,
Attribute values are limited to a certain range ).

(4) Identify the service. The operation performed after an object receives a message is called the service provided by the object. It describes the processing and functions to be executed by the system. The purpose of defining a service is to define the behavior of an object and communication between objects. The specific steps include:

-Identifies the object status

-Mark necessary services

-Identify the message connection

-Description Service

Services can be represented in a chart similar to a flow chart.

(5) Identify the topic. To better understand conceptual models that contain a large number of classes and objects, You need to identify the topic, that is, to divide the model, give the overall framework of the model, and divide the hierarchy. Follow these steps to identify a topic.

-Recognize a topic

-Improve and refine themes

-Add a topic to the analysis model.

A topic is an application-related concept, rather than manually cited. The work at the topic layer helps you understand the analysis results.

Advantages

Object-Oriented analysis mainly involves the following:

(1) enhanced understanding of problem domains and system responsibilities;

(2) improve communication between various personnel involved in analysis;

(3) strong adaptability to changes in demand;

(4) Support software reuse;

(5) consistency throughout the entire software lifecycle;

(6) practicality;

(7) conducive to user participation.

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.