信使 messenger 是微不足道的一个
它将消息封装到一个对象中到处传递
而不是将消息的所有片段分开进行传递
没有信使,translate()代码读起来非常缺乏条理
//: C10:MessengerDemo.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
#include <iostream>
#include <string>
using namespace std;
class Point { // A messenger
public:
int x, y, z; // Since it's just a carrier
Point(int xi, int yi, int zi) : x(xi), y(yi), z(zi) {}
Point(const Point& p) : x(p.x), y(p.y), z(p.z) {}
Point& operator=(const Point& rhs) {
x = rhs.x;
y = rhs.y;
z = rhs.z;
return *this;
}
friend ostream&
operator<<(ostream& os, const Point& p) {
return os << "x=" << p.x << " y=" << p.y
<< " z=" << p.z;
}
};
class Vector { // Mathematical vector
public:
int magnitude, direction;
Vector(int m, int d) : magnitude(m), direction(d) {}
};
class Space {
public:
static Point translate(Point p, Vector v) {
// Copy-constructor prevents modifying the original.
// A dummy calculation:
p.x += v.magnitude + v.direction;
p.y += v.magnitude + v.direction;
p.z += v.magnitude + v.direction;
return p;
}
};
int main() {
Point p1(1, 2, 3);
Point p2 = Space::translate(p1, Vector(11, 47));
cout << "p1: " << p1 << " p2: " << p2 << endl;
getchar();
} ///:~
输出
p1: x=1 y=2 z=3 p2: x=59 y=60 z=61
代码做你简单化处理以防止混乱
既然信使的目标只是为了携带数据
可将这些数据安排为公有成员以便访问
然而 也有理由将这些数据设为私有成员