1

例如我有一个接口和一堆类如下

public interface Drawable{
  void draw(); // draws something on screen for example.
}

abstract class Shape implements Drawable {...}
class Circle extends Shape{...} // assume that draw() is implemented in both classes.
class Square extends Shape{...} // ...

现在,如果我有一个主类并执行以下操作:

class Main{

Shape s1 = new Circle();
s1.draw(); // assume that this will draw a circle.

s1 = new Square();
s1.draw(); //assume that this will draw a square.

}

我在这里使用设计模式吗?或者这只是标准的多态性?如果这是一种设计模式,那么它叫什么?

4

2 回答 2

1
  • 在我看来,设计模式是一种久经考验编写代码来解决问题的方式。您使用给定设计模式的方式可能会因您使用的编程语言而显着不同。
  • 语言级别很少支持设计模式(尽管像 Groovy 这样的新语言确实在语言级别实现了特定的设计模式;例如,Groovy 中使用称为“闭包”的语言级别功能提供了“方法对象”模式)。
  • 您给出的代码是多态性的一个示例,它是 OOP 的基本概念之一。然而,多态性是实现许多设计模式的基础之一。
  • 语言级别支持多态性;这不是您可以将其编码到程序中的东西。
于 2013-03-06T05:55:36.020 回答
0

There was a Java book written in 1998, still available at Amazon which in Chapter 4, called out "Inteface", "Abstract Superclass" and other things as "Fundamental Design Patterns."

This claim was somewhat controversial, as many people would say these are just basic mechanisms rather than "design patterns."

Short answer is: people will give you both answers, though in my experience, most people would say no.

于 2013-03-06T05:30:51.277 回答