java各个类直接都会包含了各种关系,组合和继承关系非常多见,他们的使用方法都很相似,都是引用一个对象进来,使用其方法,但是我们什么时候使用组合,什么时候使用继承呢?
package reuse;
/**
* 模拟CAD画图
*/
public class CADSystem extends Shape {
private Circle circle;
private Triangle triangle;
private Line[] lines = new Line[3];
public CADSystem(int i) {
super(i);
for (int j = 0; j < lines.length; j++)
lines[j] = new Line(j, j * j);
circle = new Circle(1);
triangle = new Triangle(1);
System.out.println("CADSystem Contructor");
}
@Override
public void dispose() {
circle.dispose();
triangle.dispose();
for (int i = 0; i < lines.length; i++) {
lines[i].dispose();
}
super.dispose();
}
public static void main(String[] args) {
CADSystem cadSystem =new CADSystem(1);
try {
}finally {
cadSystem.dispose();
}
}
}
class Shape {
public Shape(int i) {
System.out.println("Shape Contructor");
}
//图形处理
public void dispose() {
System.out.println("Shape dispose");
}
}
class Circle extends Shape {
public Circle(int i) {
super(i);
System.out.println("");
}
@Override
public void dispose() {
System.out.println("Erasing Circle");//擦除图像
super.dispose();
}
}
class Triangle extends Shape {
public Triangle(int i) {
super(i);
System.out.println("Triangle Contructor");
}
@Override
public void dispose() {
System.out.println("Erasing Triangle");
super.dispose();
}
}
class Line extends Shape {
private int start, end;
public Line(int start, int end) {
super(start);
this.start = start;
this.end = end;
System.out.println("Drawing Line :" + start + " ." + end);
}
@Override
public void dispose() {
System.out.println("Erasing Line :" + start + " ." + end);
super.dispose();
}
}
上面是一个模拟CAD的绘图系统,这个系统使用了组合和继承,那为什么需要组合呢?这个系统的作用就是绘图,所有她继承了绘图这个类,需要 对图片做一些处理,可以看做是is-a的关系;当然它包含画圆,画三角形,画线等等很明显这是has-a的关系。
总结:当两个类在逻辑上是is-a的关系,则可以是继承;当是has-a的关系,则用组合。