Deep analysis of object concepts in object-oriented

Source: Internet
Author: User

OOP: Object-oriented programming, a reference to object-oriented, you might think of classes, interfaces. One of the characteristics, we may come to the mouth: inheritance, encapsulation, polymorphism, then exactly what kind of object (class) is the true meaning of the object? Especially now the popular DDD domain drives the design idea, stresses the responsibility division, then how defines an object (class) it should have some characteristics, the behavior method and assumes the responsibility to become the key.

A seemingly simple question, in fact, is also resistant to thinking, before also on the Internet to see some people about the design of the discussion class, think that design class should not consider the database, I think this is only to achieve the real object-oriented design of the foundation, but also the prerequisite, most programmers are subject to process-oriented programming ideas, I (Dream on the Journey) is no exception, a need to seek down, the first is to think of what data it needs to save, what tables to build, to define which methods to complete the storage of data, the whole process is basically around the database to do, I call this data-driven programming, so the development is not wrong, because there is a reason for existence I can also analyze the advantages of this programming: fast development, high execution efficiency (no hierarchy or hierarchy is just a simple forwarding), the disadvantage is: poor readability, not conducive to the subsequent two development, such as simple application or a separate core module using this programming method I think it is possible, but in addition, I still feel that reasonable object-oriented is necessary, I am here to emphasize reasonable, is not blindly adopt a framework or a design pattern, no best framework, no best design mode, only the most suitable framework and design patterns, then how to evaluate the framework and design is appropriate, I think the design of the object (class) is very important, the following is my experience and I see the phenomenon to talk about the design of the object, because I am not what Daniel, so inevitably express the wrong place, please forgive me, of course, also welcome everyone to discuss together.

1. What is the object?

In real life, the object refers to an objective thing, it has the ability to identify its uniqueness, such as: Someone's brand of a certain model of the car, why I use a number of some, because people + brand + model + car, you can determine the object, not the car so simple, Note that the car is not an object, it just represents a certain kind of things, so through the analysis of real life, we can transform ideas into the programming world, to analyze the difference between objects and classes. In programming, the class is the car above, and the object is the instantiation of the class, recognizing the uniqueness of the object from the computer's role, should be the address in the memory heap, each address to determine an object.

2. What does the object have?

An object is a specific thing, except for a property that identifies its uniqueness, it should have the following features:

One, the state (can also be simply called attributes): Describes the characteristics of an object, this feature can be permanent, or can be affected by the outside world, such as: Someone's brand of a certain model of the car, if the car re-painted, a color, then it's state at this time, The color is changed; If the car is sold to another person, then its state at this time, the owner of the car has also been changed.

code example:

    public class car//It is a class    {public        Car (string owner,string brand,string model,string color)        {This]            . Owner = owner;            This. Brand = brand;            This. model = model;            This. color = color;        }        public string Owner {get; set;}        public string Brand {get; set;}        public string Model {get; set;}        public string Color {get; set;}    }        public static void Main (string[] args)        {            var car = new Car ("Zhang San", "BMW", "B01", "Black");//This is an object            car. color = "red";//The state is changed by            car. Owner = "John Doe";//Status Changed        }

Second, the behavior (can also be simply called Methods, Functions): An object active or passive to perform some kind of action, for example: Zhang San this person, he eats, he reads books, he sleeps and so on is a kind of behavior, including I now write a blog is also a kind of behavior. Behavior is active and passive, active refers to an object subjective awareness of the action, such as: Zhang San eat is active, and passive is to need another object to command it to perform some kind of action, such as: Car start, start is a behavior, but it can not start itself, Need the driver to go through the car given the starting method and steps to request the car to perform the start, or the teller machine, the teller machine provides a withdrawal of the behavior, and when the specific time to take, take how much, all by the person to tell it.

code example:

    public class car//This is a class {public Car (string owner,string brand,string model,string color) { This.            Owner = owner; This.            Brand = brand; This.            model = model; This.        color = color;        } public string Owner {get; set;}        public string Brand {get; set;}        public string Model {get; set;}        public string Color {get; set;}        public string Status {get; private set;}        Public Driver Driver {get; set;} public void Start ()//startup method, passive {if (this. Driver!=null) {this.            Status = "in operation"; } else {throw new InvalidOperationException ("No driver, can't start automatically!")            "); }} public void Stop ()//Start method, passive {this.        Status = "Stop";        }} public class Driver {public string Name {get; set;} Public Driver (string name) {this.      name = name;  } public void drive (car car)//driving, active {car. Driver = this; Sit on the car. Start ();//boot the car and run car.            Stop ();//arrive at the end, stop the car}} public class APP9 {public static void Main (string[] args) {            var car = new Car ("Zhang San", "BMW", "B01", "Black");//This is an object var driver = new Driver ("John Doe"); Driver. Drive (car),//Lishilaika car, real life can not casually borrow car open Oh! ~v~}}

Some people look at the above code, it may be thought that not all objects have behavior, since it is the behavior, behavior and represents an action, then only the active object has the behavior, cannot move the object is not, is this? Before I wrote this blog post also thought about this question, began to think so, after careful thinking, wrong, should be all the objects have behavior, take the things that do not move, such as a piece of paper, the paper itself is not moving, but if you throw it up, then the paper has a passive move method, According to Einstein's theory of relativity, there is no absolute static, only relative static, so see under what circumstances, reference is what, a bit far away ha, return to the point, some people may still defy, all the objects have the behavior method, then I do not want to all the classes are defined methods, or not meet the real object? I don't think so, the scene determines the state and method of an object, which is also the problem I'm going to illustrate the role of positioning, and here I can be very responsible to tell you that all of our defined objects have behavior, but you don't realize it, what is it? That is, constructors and destructors, they are passive behavior methods, which is also in line with real life objects, any object has to create and destroy, you dare say not? Please cite an example!

3. Object role Positioning

Any object should have different states and behaviors in different scenes, such as: Zhang San, Zhang San in the school he is a student, has the student's condition and the behavior, works in the company he is the employee, has the employee's condition and the behavior, obtains the driving license to drive the car, has the driver's condition and the behavior, reads in the library, Have the reader's state and behavior. Thus, the object is complex, the class is specific, the object has a variability, and the class should have invariance, perhaps some people do not understand, I here specifically explain, I am here to say the variability, not the object-oriented polymorphism, but refers to the variable character of the object, such as: Student class, then it represents the students, It can not also be said that the author, of course, it may represent people, but the general people do not say so, and the object is different, as I said above Zhang San different roles, he is not the same kind of instantiation, the class does not support multiple inheritance, I think, because a class can represent a role, a role can only do this role, such as , he is learning, teacher, he is teaching, some may also say, part-time multiple roles, is the staff and the driver, but also the teacher and students, yes, there is, but said above, a part-time object can not do something at the same time, such as: Staff is also the driver, Does he work and drive at the same time, some say: Taxi Driver! Well, you're a bad guy, but it's still a different character, a taxi driver is a job, and when he's not working, he's the driver. OK, so much to say, look at the code example!

    public class person//People {public string idno{get;set;}        public string Name {get; set;}        public string Sex {get; set;}        Public double Height {get; set;}        Public double Weight {get; set;}    Public DateTime BirthDay {get; set;}        public class Post//Article {public string Title {get; set;}        public string Content {get; set;}                Public Author Author {get; set;}    Public DateTime createdatetime {get; set;}    } public class Author:person//role is author {public void Write (post post) {//behavior}}        public class book//books {public string Name {get; set;}        Public DateTime issueddate {get; set;}    Public list<post> Posts;        public class library//library {public string Name {get; set;}        Public list<book> Books {get; set;}        public void borrow (Reader reader, ienumerable<book> Books)//loan book, passive{Books.removeall (b=>books).            Contains (b)); Other operations} public void Return (Reader reader,ienumerable<book> Books)//also into the book, passive {BOOKS.A            Ddrange (books);        Other Action}} public class Reader:person//role for reader {public list<book> Books {get; set;} Public ienumerable<post> Read (book Book,params int[] pages)//reading, active {var posts = new List<p            Ost> (); if (pages! = null) {foreach (int i in pages) {posts. ADD (book.                Posts[i]); }} else {posts = book.            Posts;        } return posts; public void Borrow (Ienumerable<book> books, library library)//Active borrowing Library {library.            Borrow (This,books);        Books.addrange (Books); } public void Return (ienumerable<book> books, library library)//Active return book {library.            Return (this, books); Books.removeall (b = Books.        Contains (b)); }} public class Driver:person//role is driver {public void drive (car car) {car.            Driver = this; Car.            Start (); Car.        Stop ();        }} public class Car {public Driver Driver {get; set;}        public string status{get;private set;} public void Start () {this.        status= "in operation"; } public void Stop () {this.        Status= "Stop"; }    }

End

I'm just defining this, not listing the run-time code. The example is quite simple, let's look at it just fine. Finally, although the object has state and behavior, and the role of different states and behavior is different, but in the programming world, we can only focus on our concerns, such as: a blog system, we only focus on the author, readers, respondents three characters, From the three roles should have the status and behavior of the design-related classes, so that more in line with the real object, it will not appear common: State Class-Zombie class (only attributes, no method), method class-Ghosts of Wild Ghost Class (only method, no attribute)


Well, the article ended here, the object-oriented thinking is broad and profound, it is difficult to say all of a sudden, but I believe that as long as we in the programming of more than a summary can enhance our programming awareness, one day become a master. In this tribute to the master, Daniel, learn from you, the path of learning is always endless. This article I spent a morning of time, think a lot, but not many, but all from my idea, if help to everyone, also please support recommend Oh, thank you very much!

Deep analysis of object concepts in object-oriented

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.