让我说我有一个带有draw()方法的抽象类Shape。还有两个类,Circle和Triangle,它们扩展了Shape类,超越了超级类#&绘制方法。我使用Pen资源绘制任一形状。我想在调用sub classdraw()方法后立即释放(关闭或取消)Pen资源,但必须在Parent类中完成。我们怎样才能做到这一点?
这只是我尝试创建上述场景的示例代码(可能无法完全重现上述情况)
class Pen {
Pen() {
System.out.println("Pen initialized");
}
public void drawShape(Shape s) {
if(s instanceof Circle) {
System.out.println("Drawn Circle");
} else if(s instanceof Triangle) {
System.out.println("Drawn Triangle");
}
}
public void close() {
System.out.println("Released pen resource");
}
}
abstract class Shape {
Pen pen;
Shape() {
pen = new Pen();
System.out.println("Shape constructor");
}
public void draw() {
System.out.println("Draw Shape");
}
}
class Circle extends Shape {
Circle() {
System.out.println("Circle constructor");
}
public void draw() {
super.pen.drawShape(this);
}
}
class Triangle extends Shape {
Triangle() {
System.out.println("Triangle constructor");
}
public void draw() {
super.pen.drawShape(this);
}
}
public class ShapeTest {
public static void main(String args[]) {
Shape s = new Triangle();
s.draw();
}
}
在上面的代码中,如何在执行子类'之后调用Pen类的close()方法。 draw方法并在超类本身中释放Pen资源?
答案 0 :(得分:1)
这是你在找什么?
abstract class Shape {
Pen pen;
Shape() {
pen = new Pen();
System.out.println("Shape constructor");
}
protected void draw() {
System.out.println("Draw Shape");
}
public void doDraw() {
draw();
pen.close();
}
}
直接致电doDraw()
而非draw()
。我将draw
的可见度更改为protected
答案 1 :(得分:1)
对于这种情况,我将应用模板方法模式。它看起来像这样:
abstract class Shape {
Pen pen;
Shape() {
pen = new Pen();
System.out.println("Shape constructor");
}
abstract void drawImpl();
public void draw() {
System.out.println("Draw Shape");
drawImpl();
pen.close();
}
}
现在,您可以覆盖draw()
,而不是覆盖drawImpl()
,如下例Circle
类所示:
class Circle extends Shape {
Circle() {
System.out.println("Circle constructor");
}
void drawImpl() {
super.pen.drawShape(this);
}
}
模板方法模式可以应用于可以将算法分解为不同操作的任何位置,每个操作都可以独立地重写。 wikipedia page有一个很好的解释,图表和示例代码。
答案 2 :(得分:0)
使用模板方法模式后,以下工作正如Ken Wayne VanderLinde所建议的那样
class Pen {
Pen() {
System.out.println("Using Pen");
}
public void draw(Shape s) {
if(s instanceof Circle) {
System.out.println("Draw Circle");
} else if(s instanceof Triangle) {
System.out.println("Draw Triangle");
}
}
public void close() {
System.out.println("Pen resource closed");
}
}
abstract class Shape {
Pen pen;
Shape() {
pen = new Pen();
}
abstract public void draw();
public void drawShape() {
draw();
pen.close();
}
}
class Circle extends Shape {
public void draw() {
super.pen.draw(this);
}
}
class Triangle extends Shape {
public void draw() {
super.pen.draw(this);
}
}
public class TemplateMethodTest {
public static void main(String[] args) {
Shape s = new Triangle();
s.drawShape();
}
}
以下是输出
Using Pen
Draw Triangle
Pen resource closed