1 / 42

Design Patterns in Java Part I Interface Patterns Chapter 2 Introducing Interfaces

Design Patterns in Java Part I Interface Patterns Chapter 2 Introducing Interfaces. Summary prepared by Kirk Scott. What is an Interface?. Speaking not about Java specifically, but generally, an interface is the set of methods (and variables) that one class allows other classes to access

harlan
Télécharger la présentation

Design Patterns in Java Part I Interface Patterns Chapter 2 Introducing Interfaces

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Design Patterns in JavaPart IInterface PatternsChapter 2Introducing Interfaces Summary prepared by Kirk Scott

  2. What is an Interface? • Speaking not about Java specifically, but generally, an interface is the set of methods (and variables) that one class allows other classes to access • Again, speaking very generally and imprecisely, but using Java as an example, a class’s interface is its set of public methods (and any instance variables which may be public)

  3. What is an Interface? Cont’d. • Notice that naming is of some importance when writing code • If a method has a name which implies that it performs a certain action, then it is important that the name and the action agree • At a higher level, from the interface point of view, a class’s interface is a commitment to perform the actions implied by the names of the methods in the interface

  4. What is an Interface? Cont’d. • A class implements a given interface by means of the code in its methods • The interface is defined by what it does, not how it’s implemented • Java abstracts the idea of an interface into a separate construct • An interface itself can have an independent definition and multiple classes can implement the same interface • Likewise, a given class can implement more than one interface • Among the other purposes they serve in Java, interfaces substitute for multiple inheritance

  5. What is an Interface? Cont’d. • The point of part I of the book is that it is possible to go beyond the basic function provided by the interface syntax in Java • Rather than trying to explain this in advance, let it be said that “going beyond” will be explained when the patterns are introduced • Also, before trying to “go beyond” it is useful to review in more detail what simple interfaces in Java can do

  6. Interfaces and Abstract Classes • Note that other object-oriented languages, such as C++ and Smalltalk, do not have an interface construct • Such languages make use of abstract classes to accomplish what can be done with interfaces • In general, abstract classes and interfaces are similar, but as implemented in Java, they are distinguished from each other by certain characteristics

  7. Interfaces and Abstract Classes, cont’d. • Challenge 2.1 • Write down [at least] three differences between abstract classes and interfaces in Java.

  8. Interfaces and Abstract Classes, cont’d. • Solution 2.1 • An abstract class with no non-abstract methods is similar to an interface in terms of its utility. However, note the following: • A class can implement any number of interfaces but can subclass at most one abstract class. • An abstract class can have non-abstract methods; all the methods of an interface are effectively abstract

  9. Interfaces and Abstract Classes, cont’d. • Solution 2.1, cont’d. • An abstract class can declare and use fields; an interface cannot, although it can create static final constants. • An abstract class can have methods whose access public, protected, private, or none (package). An interface’s methods are implicitly public. • An abstract class can define constructors; an interface cannot.

  10. Interfaces and Abstract Classes, cont’d. • The book asserts the following about interfaces: • It is possible to live without interfaces, using abstract classes instead, (witness C++) • However, they are especially useful in “n-tier development” • Thus, the inclusion of them as a separate concept in a language such as Java is very useful

  11. Interfaces and Abstract Classes, cont’d. • The authors then provide this example of a definition of an interface in Java: • public interface RocketSim • { • abstract double getMass(); • public double getThrust(); • void setSimTime(double t); • }

  12. Interfaces and Abstract Classes, cont’d. • Challenge 2.2 consists of 7 true or false questions, A-G, about the RocketSim interface • The interface code is repeated and the questions are treated one at a time in the following overheads • Several of the questions seem to result simply from coding practices that originate in C++, for example • The authors don’t intend them as trick questions, but the questions only arise because code is written in a way that a dyed in the wool Java programmer probably wouldn’t write it anyway

  13. Interfaces and Abstract Classes, cont’d. • Some of the questions are deceptive simply because the answer is so obvious • Finally, some of the questions seem useful because they reinforce some aspect of Java syntax that may not be obvious or may have slipped your mind • They should all be taken for whatever they’re worth

  14. public interface RocketSim • { • abstract double getMass(); • public double getThrust(); • void setSimTime(double t); • } • Question A. All three methods of the RocketSim interface are abstract, although only getMass() declares this explicitly. [T or F] • Note that this is one of the “trick” questions, because as a Java programmer, there was never any need to declare a method abstract in an interface definition—see the book’s answer.

  15. Solution 2.2, A • True. Interface methods are always abstract, whether or not they declare it. • In other words, this question merely reinforces explicitly what a Java programmer already knows implicitly • If a method is abstract, the subclass has to implement the method • If a method appears in an interface definition, the implementing class has to implement the method

  16. public interface RocketSim • { • abstract double getMass(); • public double getThrust(); • void setSimTime(double t); • } • Question B. All three methods of the interface are public, although only getThrust() declares this explicitly. [T or F] • Note that this is also one of the “trick” questions, because as a Java programmer, there was never any need to declare a method public in an interface definition—see the book’s answer.

  17. Solution 2.2, B • True. Interface methods are public, whether or not they declare it. • In other words, this question merely reinforces what a Java programmer already knows (and this is not a matter of implicit or explicit knowledge) • It may not be a bad idea to declare methods in an interface public as a reminder that they are so, but there is no need to, because interface methods are public by default • Note that trying to give an interface method some other access modifier would be a mistake

  18. public interface RocketSim • { • abstract double getMass(); • public double getThrust(); • void setSimTime(double t); • } • Question C. The interface is declared “public interface”, but it would be public even if the public keyword were omitted. [T or F] • I do not classify this as a trick question. The answer is straightforward, and it seems to me that the point of the question is to keep you from carelessly assuming that the rules that apply to the access modifiers of interface methods do not apply to the interface itself—see the book’s answer.

  19. Solution 2.2, C • False. An interface’s visibility may be limited to the package in which it resides. In this case, it is marked public, so classes outside com.oozinoz.simulation can access it. • Notice that this answer doesn’t address the question of whether or not it would be syntactically possible or in any way useful to declare an interface either private or protected

  20. public interface RocketSim • { • abstract double getMass(); • public double getThrust(); • void setSimTime(double t); • } • Question D. It is possible to create another interface, say, RocketSimSolid, that extends RocketSim. [T or F] • Note that as far as I recall, this is a new question—something that hasn’t been considered before.

  21. Solution 2.2, D • True. For example, the List and Set interfaces both extend the Collection interface in java.util. • …So in fact, somewhere in previous material this might have been evident, when delving through the Java API for the collection classes… • Note that there is a logic to it: If interfaces are the vehicle for multiple inheritance, why shouldn’t interfaces be arranged in inheritance hierarchies?

  22. public interface RocketSim • { • abstract double getMass(); • public double getThrust(); • void setSimTime(double t); • } • Question E. Every interface must have at least one method. [T or F] • Note that as a matter of fact, we have encountered the answer to this question before, but it might not spring immediately to mind.

  23. Solution 2.2, E • False. An interface with no methods is known as a marker interface. Sometimes, a method high in a class hierarchy, such as Object.clone(), is not appropriate for every subclass. You can create a marker interface that requires subclasses to opt in or opt out of participation in such a scheme. The clone() method on Object requires subclasses to opt in, by declaring that they implement the Cloneable interface. • The news in this answer seems to be that an application programmer could also implement a method and matching marker interface in a hierarchy of non-system classes

  24. public interface RocketSim • { • abstract double getMass(); • public double getThrust(); • void setSimTime(double t); • } • Question F. An interface can declare instance fields that an implementing class must also declare. [T or F] • This is a completely straightforward question about Java syntax. The only possible source of confusion might be the wording.

  25. Solution 2.2, F • False. An interface cannot declare instance fields, although it can create constants by declaring fields that are static and final. • In other words, as you know, an interface definition can’t include any instance variables • The news in this answer is that interfaces can make constant values available to implementing classes

  26. public interface RocketSim • { • abstract double getMass(); • public double getThrust(); • void setSimTime(double t); • } • Question G. Although you can’t instantiate an interface, an interface definition can declare constructor methods that require an implementing class to provide constructors with given signatures. [T or F] • This question hasn’t been considered before, but as with the trick questions, when you see the answer, you’ll know why.

  27. Solution 2.2, G • False. It might be a good idea, but there is no way for a Java interface to require that implementing classes provide a particular constructor • In other words, the reason this never came up before is because it is not possible in Java • When you learn a language, you spend all your time learning what’s not possible, not mooning about what might be desirable but not possible • Once you get to a “higher” level (like design patterns) then you start mooning, although it’s not immediately apparent to me that having this feature in Java would be either particularly desirable or undesirable

  28. Interfaces and Obligations • Considering interfaces in their general sense as the set of methods and variables a class makes available, interfaces limit the interactions between objects • It’s the same old story of object orientation—namely, it’s another aspect of encapsulation • The limitation is an advantage, not a disadvantage

  29. Interfaces and Obligations, cont’d. • The internal implementation of the interface may change, but a client is insulated from this and need only know the interface itself • In general, a programmer is obligated to provide implementations if a class implements an interface • The authors point out that in certain, relatively special circumstances, it is not necessary to implement the interface

  30. Interfaces and Obligations, cont’d. • Challenge 2.3 • Give an example of an interface with methods that do not imply responsibility on the part of the implementing class to return a value or even to take any action on behalf of the caller at all. • Note that this is a rather unfair exercise in mind reading. However, the answer will be something familiar and it’s a useful way of taking a new look at something you’ve already heard about before

  31. Interfaces and Obligations, cont’d. • Solution 2.3 • One example occurs when classes may be registered as listeners for events; the classes receive notification for their own benefit, not the caller’s. For example, we may want to take action on MouseListener.mouseDragged() but have an empty body for MouseListener.mouseMoved() for the same listener.

  32. Interfaces and Obligations, cont’d. • As you already know, a way to simplify the implementation in such cases is by writing what is known as an adapter class in Java • This book uses the term adapter to refer to a design pattern; the book uses the term stub to refer to what Java calls an adapter class • The book mentions the WindowAdapter class as an example; clearly the implementation of mouse listeners would be another example

  33. The next overhead shows a UML diagram of a Java adapter class • The adapter class implements the interface, providing dummy implementations of all of the required methods

  34. Interfaces and Obligations, cont’d. • There were no examples of this in CS 202, but as mentioned, it is possible to declare constants in an interface • This is the book’s example code: • public interface ClassificationConstants • { • static final int CONSUMER = 1; • static final int DISPLAY = 2; • }

  35. Summary • Note, first of all, that material follows the summary (the authors’ logic is unique in this regard) • This is the book’s summary of the chapter, verbatim: • The power of interfaces is that they delineate what is and isn’t expected in how classes collaborate. • Interfaces are similar to purely abstract classes, defining expectations but not implementing them.

  36. Summary, cont’d. • Mastering both the concepts and the details of applying Java interfaces is well worth the investment of your time. • This powerful construct is at the heart of many strong designs and several design patterns.

  37. Beyond Ordinary Interfaces • There are four design patterns in this section which “go beyond” what is available when simply using straight Java interface syntax • Intent: Adapt a class’s interface to match the interface a client expects. Pattern: Adapter • Intent: Provide a simple interface into a collection of classes. Pattern: Façade

  38. Beyond Ordinary Interfaces, cont’d. • Intent: Define an interface that applies to both individual objects and groups of objects. Pattern: Composite • Intent: Decouple an abstraction from its implementation so that the two can vary independently. Pattern: Bridge

  39. Beyond Ordinary Interfaces • The intent of each design pattern is to solve a problem in a context. • Interface-oriented patterns address contexts in which you need to define or redefine access to the methods of a class or group of classes. • For example, when you have a class that performs a service you need but with method names that do not match a client’s expectations, you can apply the Adapter pattern

  40. Beyond Ordinary Interfaces • Notice that the previous bullet comes the closest so far to giving a concrete explanation of one use of a design pattern • One class has methods which do the desired thing but another class needs to call methods with different names • Understanding this fully will require understanding which class is which in the terminology “client” and “perform service” • The next chapter is completely devoted to explaining the Adapter design pattern

  41. The End

More Related