Interfaces

In Java, the usual mechanism for supporting this form of abstraction is the interface. The interface mechanism provides a means for dispatching calls to an abstract function, specified in an interface definition, to a specific implementation based on the datatype of the first parameter passed in the call. In Java, the first parameter is implicit; it’s the object that implements the interface.

Following are the strengths of interfaces:

  • Datatypes can implement multiple interfaces.
  • Interfaces provide only specification, not implementation, which allows implementation of multiple interfaces without the problems associated with multiple class inheritance.

The weakness of interfaces is that existing datatypes cannot be extended to implement new interfaces without rewriting them.

We can create Java interfaces in Clojure with the definterface macro. This takes a name and one or more method signatures:

 (definterface name & sigs)

Let’s create our abstraction for things-that-can-be-read-from-and-be-written-to as an interface, which we’ll call IOFactory.

 (definterface IOFactory
  (^java.io.BufferReader make-reader [this])
  (^java.io.BufferedWriter make-writer [this]))

This will create an interface called IOFactory that includes two abstract functions, make-reader and make-writer. Any class that implements this interface must include make-reader and make-writer functions that take a single parameter and an instance of the datatype itself and return a BufferedReader and BufferedWriter, respectively.

Unfortunately, the interfaces that a class supports are determined at design time by the author; once a Java class is defined, it cannot be updated to support new interfaces without rewriting it. Therefore, we can’t extend the File, Socket, and URL classes to implement the IOFactory interface.

Like the versions of make-reader and make-writer we based on condp, our interface is closed to extension by parties other than the author. This is part of what is called the expression problem.[35] Fortunately, Clojure has a solution to it.[36]

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.220.22