当然,我们需要在每种Shape的类里面提供draw这个方法:
abstract class Shape {
abstract void draw(Graphics graphics);
}
class Line extends Shape {
Point startPoint;
Point endPoint;
void draw(Graphics graphics) {
graphics.drawLine(getStartPoint(), getEndPoint());
}
}
class Rectangle extends Shape {
Point lowerLeftCorner;
Point upperRightCorner;
void draw(Graphics graphics) {
graphics.drawLine(...);
graphics.drawLine(...);
graphics.drawLine(...);
graphics.drawLine(...);
}
}
class Circle extends Shape {
Point center;
int radius;
void draw(Graphics graphics) {
graphics.drawCircle(getCenter(), getRadius());
}
}
将抽象类变成接口
现在,看一下Shape这个类,它本身没有实际的方法。所以,它更应该是一个接口:
interface Shape {
void draw(Graphics graphics);
}
class Line implements Shape {
...
}
class Rectangle implements Shape {
...
}
class Circle implements Shape {
...
}
改进后的代码
改进后的代码就像下面这样:
interface Shape {
void draw(Graphics graphics);
}
class Line implements Shape {
Point startPoint;
Point endPoint;
void draw(Graphics graphics) {
graphics.drawLine(getStartPoint(), getEndPoint());
}
}
class Rectangle implements Shape {
Point lowerLeftCorner;
Point upperRightCorner;
void draw(Graphics graphics) {
graphics.drawLine(...);
graphics.drawLine(...);
graphics.drawLine(...);
graphics.drawLine(...);
}
}
class Circle implements Shape {
Point center;
int radius;
void draw(Graphics graphics) {
graphics.drawCircle(getCenter(), getRadius());
}
}
class CADapp {
void drawShapes(Graphics graphics, Shape shapes[]) {
for (int i = 0; i < shapes.length; i++) {
shapes[i].draw(graphics);
}
}
}
如果我们想要支持更多的图形(比如:三角形),上面没有一个类需要修改。我们只需要创建一个新的类Triangle就行了。
上一篇:Java抽象类的相关介绍
下一篇:初见python你对它了解多少?
¥498.00
¥399.00
¥299.00
¥29.00