(Simplifying Idioms)
在获得更复杂的技巧之前,去看看一些保持代码简洁基本的方式是有所帮助的。
其中更琐碎的是消息,他简化了包信息到一个对象中被用来传递,而不是分离的传递所有的片断。注意没有消息的话,translate()这个代码读起来会让人更加迷惑:
//: simplifying:MessengerDemo.java
package simplifying;
import junit.framework.*;
class Point { // A messenger
public int x, y, z; // Since it's just a carrier
public Point(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public Point(Point p) { // Copy-constructor
this.x = p.x;
this.y = p.y;
this.z = p.z;
}
public String toString() {
return "x: " + x + " y: " + y + " z: " + z;
}
}
class Vector {
public int magnitude, direction;
public Vector(int magnitude, int direction) {
this.magnitude = magnitude;
this.direction = direction;
}
}
class Space {
public static Point translate(Point p, Vector v) {
p = new Point(p); // Don't modify the original
// Perform calculation using v. Dummy calculation:
p.x = p.x + 1;
p.y = p.y + 1;
p.z = p.z + 1;
return p;
}
}
public class MessengerDemo extends TestCase {
public void test() {
Point p1 = new Point(1, 2, 3);
Point p2 = Space.translate(p1, new Vector(11, 47));
String result = "p1: " + p1 + " p2: " + p2;
System.out.println(result);
assertEquals(result,"p1: x: 1 y: 2 z: 3 p2: x: 2 y: 3 z: 4");
}
public static void main(String[] args) {
junit.textui.TestRunner.run(MessengerDemo.class);
}
} ///:~
因为消息的目的仅仅是传输数据,并且那些数据为public属性容易访问。然而你或许会有些原因让它置为private。
消息的老大就是参数收集,它的职能就是从方法中捕捉信息到他所传递的对象中去。一般来,说当收集的参数被传递到多个方法中去的时候就会被用到,像一个蜜蜂采集花粉一样。
容器起到了一个特别有用的参数收集的作用,因此它早已被用来动态的添加对象。
//: simplifying:CollectingParameterDemo.java
package simplifying;
import java.util.*;
import junit.framework.*;
class CollectingParameter extends ArrayList {}
class Filler {
public void f(CollectingParameter cp) {
cp.add("accumulating");
}
public void g(CollectingParameter cp) {
cp.add("items");
}
public void h(CollectingParameter cp) {
cp.add("as we go");
}
}
public class CollectingParameterDemo extends TestCase {
public void test() {
Filler filler = new Filler();
CollectingParameter cp = new CollectingParameter();
filler.f(cp);
filler.g(cp);
filler.h(cp);
String result = "" + cp;
System.out.println(cp);
assertEquals(result,"[accumulating, items, as we go]");
}
public static void main(String[] args) {
junit.textui.TestRunner.run(CollectingParameterDemo.class);
}
} ///:~
参数收集必须有某种方式来设置或插入数据。注意通过这种定义,消息能够被用作收集的参数,关键在于参数集合被传递到他所传递倒的方法,并且能够被这个方法修改。
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/25966/viewspace-53313/,如需转载,请注明出处,否则将追究法律责任。