“组合”是代码复用的一种有效手段,帮助你通过不同数据类型之间的融合产生新的更具威力的类型。 不同于继承,虽然两者都是复用的极佳工具,但组合提供了一种动态体系结构,使得你可以更灵活的在运行时决定调用的类型,而继承是一种静态体系结构,一旦继承就无法改变父子关系。继承代码重用的事例: class Father { protected int i = 5; protected void print() { System.out.println("This 'i' is belong to Father, but be called from Son: " + i); } }class Son extends Father { }class Test { public static void main(String[] args) { Son s = new Son(); // Call print() method s.print(); } }使用复合支持代码重用 class Component { private int i = 5; public void print() { System.out.println("This 'i' is belong to Component, but be called from Son: " + i); } }class Another { private Component c = new Component(); public void print() { c.print(); } }class Test { public static void main(String[] args) { Another other = new Another(); // Call print() method other.print(); } }@.@||~
多看些软件工程的book
1。针对接口编程
2。邮箱使用组合,而不是继承
3。找到并封装变化点
组成是被包容的对象是包容对象的一部分,即缺少了不可,例如引擎对于汽车
而相对的继承,就是一种“is-a”的关系。
不同于继承,虽然两者都是复用的极佳工具,但组合提供了一种动态体系结构,使得你可以更灵活的在运行时决定调用的类型,而继承是一种静态体系结构,一旦继承就无法改变父子关系。继承代码重用的事例:
class Father {
protected int i = 5;
protected void print() {
System.out.println("This 'i' is belong to Father, but be called from Son: " + i);
}
}class Son extends Father { }class Test {
public static void main(String[] args) {
Son s = new Son();
// Call print() method
s.print();
}
}使用复合支持代码重用
class Component {
private int i = 5;
public void print() {
System.out.println("This 'i' is belong to Component, but be called from Son: " + i);
}
}class Another {
private Component c = new Component();
public void print() {
c.print();
}
}class Test {
public static void main(String[] args) {
Another other = new Another();
// Call print() method
other.print();
}
}@.@||~