Olivier
8/19/2007 2:17:00 AM
> > Steve Quezadas <steve@tripperjones.com> wrote:
> > Please forgive this rather naive question, but it's a query that's
> > difficult to search for on google. In java, you can program to
> > interface. IE, in java, you can do:
> >
> > public interface QuakeBehavior {
> > public void quack();
> > }
> >
> > public class Quack implements QuckBehavior {
> > public void quack() {
> > System.out.println("Quack");
> > }
> > }
> >
> > public class Squeek implements QuackBehavior {
> > public void quack() {
> > System.out.println("Squeek");
> > }
> > }
> >
> > public class MuteQuack implements QuackBehavior {
> > public void quack() {
> > System.out.println("<< Silence >>");
> > }
> > }
> >
> > I am learning about Design Patterns (which is a wonderful concept), but
> > I want to know the Ruby equivalent.
> >
> > - steve
Le samedi 18 août 2007 23:59, Deepak Vohra a écrit :
> Steve,
>
> The Ruby equivalent of Java's interface is module.
>
> Deepak
>
I disagree : the equivalent of java's interface is implicit interface. That
is, two objects implement an interface if they can respond to a common set of
methods. There is no need to explicitly declare, like in java with
the "interface" construction, this set of methods. This is possible because
of the dynamic typing of Ruby. You can search the keywords "duck typing", for
more details.
It has the advantage of being more concise, faster to write, and avoids
repetitions of method declarations . The disadvantage is that there is not
dedicated places to formally define the interfaces.
Modules are constructs that allow to define a bunch of methods to be "copied"
inside a class. Of course, every classes that include the same module share
the same interface, since they copied the same methods. If you want to
compare to java, modules are more similar to java's abstract classes. The
difference is that java allows a class to inherit from only one abstract
class, when a ruby class can include many modules.
If you really want to have a place to explicitly define an interface, you can
declare fake methods in a module :
module QuakeBehavior
def quack
raise NotImplementedError.new
end
end
class Squeek
include QuakeBehavior
def quack
puts 'squeek'
end
end
Note that the method 'quack' from class 'Squeek' replaces the definition of
the method 'quack' that was first included from 'QuakeBehavior'.
If you use this technique, you will be warned by a NotImplementedError (so, at
runtime), if you forgot to define a method in classes that include
QuakeBehavior. I don't think it is a good design, but maybe it can help.
--
Olivier Renaud