在Programming Abstractions in C++ pp.129遇到了面向对象中messages这个概念:
- “In the object-oriented world, objects communicate by sending information and requests from one object to another. Collectively, these transmissions are called messages. The act of sending a message corresponds to having one object invoke a method that belongs to a different object. For consistency with the conceptual model of sending messages, the object that initiates the method is called the sender, and the object that is the target of that transmission is called the receiver.” How to understand this sentence?
This passage describes a fundamental concept in object-oriented programming (OOP) — the idea of objects communicating with each other through the mechanism of sending and receiving messages. Here’s a breakdown to help understand this concept:
Objects: In OOP, an object is an instance of a class (一个对象是一个类的实例). A class defines a blueprint for an object, including its data (attributes or properties) and behaviors (methods or functions).
Messages: When we say objects communicate by sending messages, we’re referring to the process of one object calling a method of another object. In OOP, a message is not like a text message or an email; instead, it’s a metaphor for invoking methods on objects.
Sending a Message: This corresponds to one object (the sender) calling or invoking a method that belongs to another object (the receiver). For example, if we have an objectdog
of classDog
and we calldog.bark()
, we are sending abark
message to thedog
object.
Method Invocation: The method that is called or invoked on the receiver object is defined within the class of that object. It determines how the object responds to the message. Using the previous example, thebark
method defined in theDog
class dictates what happens when thebark
message is sent to aDog
object.
Sender and Receiver: In the context of a message:
The sender is the object that initiates the method call.
The receiver is the object whose method is being called.
Conceptual Model: The idea of “sending messages” is more of a conceptual model in OOP. It helps to think about objects as independent entities that interact by sending requests (messages) to each other, rather than directly accessing each other’s data or state.class Dog { public: void bark() { std::cout << "Woof!" << std::endl; } }; int main() { Dog myDog; // 'myDog' is an object of class 'Dog' myDog.bark(); // Sending a 'bark' message to 'myDog' }
In this example:
myDog.bark()
is akin to sending abark
message to themyDog
object.myDog
is the receiver of the message, and themain
function (or the runtime environment that calls main) can be thought of as the sender.This model of communication encapsulates (封装) behavior within objects and promotes a design where objects interact through well-defined interfaces, a key principle in object-oriented design.