1 / 68

Chapter 9 : Interfaces

Chapter 9 : Interfaces. Objectives. After studying this chapter you should understand the following: the role of abstraction in the specification of a server; the use of interfaces to specify servers independent of implementation details;

jana
Download Presentation

Chapter 9 : 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. Chapter 9 : Interfaces

  2. Objectives • After studying this chapter you should understand the following: • the role of abstraction in the specification of a server; • the use of interfaces to specify servers independent of implementation details; • the notion of subtype, and fundamental property of a subtype; • contractual requirements in the implementation of an interface; • multiple inheritance of interfaces; • the notion and use of the strategy pattern. • Also, you should be able to: • specify and implement an interface; • use an interface to capture commonality among similar classes. NH-Chapter 9

  3. Modeling alternative implementations • Nim game implementation models class Player responsible for making a move according to Game rules. • Strategies Player can implement when making a move: • Timid strategy • Greedy strategy • Clever strategy NH-Chapter 9

  4. Modeling alternative implementations • Player abstraction and Player clients should be • independent of implementations; • independent of strategies chosen; • implementations must respect the abstraction’s contract:Player makes a move according to Game rules. NH-Chapter 9

  5. Java interfaces • A Java interface is used to specify minimal functionality that a client requires of a server. • A Java interface contains: • method specifications, called abstract methods, and • named constant definitions. • A Java interface does not contain: • constructors, • method bodies, • instance variables. NH-Chapter 9

  6. Player interface interface Player { public String name (); publicint sticksTaken (); publicvoid takeTurn (Pile pile, int maxOnATurn); } NH-Chapter 9

  7. Java interfaces • An interface can be • public , or • package private. • Method specifications in an interface are by default: • public, and • abstract (only specification with no implementation). NH-Chapter 9

  8. Java interface implementation • A class implements an interface by • naming interface in an implementsclause in class heading, and • including definitions for all methods in the interface. NH-Chapter 9

  9. Java interface implementation class TimidPlayer implements Player { public String name () { … } publicint sticksTaken (){ … } publicvoid takeTurn (Pile pile, int maxOnATurn) { … } } NH-Chapter 9

  10. Java interface implementation • Static diagram display of relation between interface Player and classTimidPlayer NH-Chapter 9

  11. is-a Java interface • Interface Player abstractsTimidPlayer, GreedyPlayer, andCleverPlayer NH-Chapter 9

  12. Interface and types • An interface defines a type. • A value is in the interface type if it references an instance of a class that implements the interface. • A value of type reference-to-TimidPlayer, is also of type reference-to-Player. • A value of type reference-to-GreedyPlayer, is also of type reference-to-Player. • A value of type reference-to-CleverPlayer is also of type reference-to-Player. NH-Chapter 9

  13. Interface and types • The type reference-to-TimidPlayer is said to be a subtype of the type reference-to-Player. • The type reference-to-GreedyPlayer is said to be a subtype of the type reference-to-Player. • The type reference-to-CleverPlayer is said to be a subtype of the type reference-to-Player. NH-Chapter 9

  14. Interface and types • Reference-to-Player is a supertype of • reference-to-TimidPlayer. • reference-to-GreadyPlayer. • reference-to-CleverPlayer. NH-Chapter 9

  15. Terminology • Simplify terminology: refer to reference types by class or interface name. Thus we say “type Player” rather than “type reference-to-Player.” NH-Chapter 9

  16. Interfaces and types • A type defined by an interface can be used like any other reference type. • It can be the type of an instance variable or parameter, • It can be the return type of a query. NH-Chapter 9

  17. Interfaces and types:Rewriting Game • Can define class Gameexactly as in Listing 8.3, even if Player is an interface and not a class. • Instance variables can be of type Player: • queries can return values of type Player: private Player player1; private player player2; • constructors and methods can have Player parameters: public Game (Player player1, Player player2, int sticks) public Player nextPlayer () … NH-Chapter 9

  18. Types and Subtypes • If client expects server of type Player, then a value of any Playersubtype can be provided. • Subtype rules: • if type A is a subtype of type B, then • an A value can be provided wherever a B value is required. • an A expression can be writtenwherever a B value is required. NH-Chapter 9

  19. Types and Subtypes • Thus for Game constructor: • It can be specified with parameters of type Player interface; • it can be invoked with arguments referencing TimidPlayers, GreedyPlayers, CleverPlayers. NH-Chapter 9

  20. Static types • The Game method nextPlayer is specified as • If game is a Game instance, Player is the static type of expression public Player nextPlayer () The Player whose turn is next. game.nextPlayer() NH-Chapter 9

  21. Dynamic types • When game.nextPlayer() is evaluated during execution, value returned will reference an specific object: • If an instance of TimidPlayer. Then dynamic type of value returned by expression is TimidPlayer. • If an instance of GreedyPlayer. Then dynamic type of value returned by expression is GreedyPlayer. • If an instance of CleverPlayer. Then dynamic type of value returned by the expression is CleverPlayer. • The dynamic type is always a subtype of Player. NH-Chapter 9

  22. Types and Subtypes • The following require expressions of type Player: private Player nextPlayer; privatevoid reportPlay (Player player) … public Player winner () … nextPlayer = Player expression required; reportPlay(Player expression required); public Player winner () { … returnPlayer expression required; } NH-Chapter 9

  23. Types and Subtypes • Given: • The following are legal:: TimidPlayer timid = new TimidPlayer("Wakko"); nextPlayer = timid; reportPlay(timid); public Player winner () { … returntimid; } NH-Chapter 9

  24. Types and Subtypes • If game is a Game instance, we cannot write the following: • Assignment operator requires a TimidPlayer on the right. • game.nextPlayer() is of type Player, and • Player is not a subtype of TimidPlayer. TimidPlayer next = game.nextPlayer(); NH-Chapter 9

  25. Types and Subtypes Player p1; Player p2; TimidPlayer tp = new TimidPlayer("Wakko"); CleverPlayer cp = new CleverPlayer("Guy"); p1 = tp p1 = tp p2 = cp p2 = p1 NH-Chapter 9

  26. Types and Subtypes • The following are not legal: tp = p1; // p1 is not of type TimidPlayer cp = p2; // p2 is not of type CleverPlayer cp = tp; // tp is not of type CleverPlayer NH-Chapter 9

  27. Revised Nim game • Classes Pile and Game remain the same. • Game constructors, methods, and instance variables are written in terms of type Player. • NimTUI will still have instance variables of type Player: private Player player1; private Player player2; NH-Chapter 9

  28. Revised Nim game • Initialization code will create specific kinds of players. public NimTUI () { this.player1 = new TimidPlayer("Player1"); this.player2 = new GreedyPlayer("Player2"); this.game = null; this.in = new BasicFileReader(); } NH-Chapter 9

  29. Implementing classes and contracts Client interface promises this interface requires this server delivers this server accepts this Server server class can be more conservative in server class can be more liberal in what it delivers (stronger postconditions) what it accepts (weaker preconditions) than what is specified by the interface than what is specified by the interface NH-Chapter 9

  30. Interface Movable NH-Chapter 9

  31. Interface Weapon «interface» wields Explorer Weapon Sword Pen MissileLauncher NH-Chapter 9

  32. Multiple inheritance of interfaces class Sword implements Weapon, Movable {…} NH-Chapter 9

  33. Interface extension • Assume all weapons are movable: interface Weapon extends Movable {…} NH-Chapter 9

  34. Extending more than 1 interface • An interface can extend more than one interface. • interfaceDataIOextendsDataInput, DataOutput { } NH-Chapter 9

  35. Modifying Nim: user vs. computer • Want same simple nim game and text-based user interface • Want user to play against “the computer” rather than just watching the game. NH-Chapter 9

  36. Modifying Nim: user vs. computer • need two different kinds of players. • One player decides its own move; • the other gets its move from an external source, the user. NH-Chapter 9

  37. Modifying Nim: user vs. computer • Define two classes • IndependentPlayer, and • InteractivePlayer. • Both classes implement interface Player. • IndependentPlayer is specified exactly as the class Player was in Chapter 8. • The InteractivePlayer, gets its move from a client. NH-Chapter 9

  38. Interactive player specifications class InteractivePlayer implements Player A player in the game simple nim that gets moves from a client. public InteractivePlayer (String name) Create a new InteractivePlayer with the specified name. ensure: this.name().equals(name) public String name () This InteractivePlayer’s name. publicint sticksTaken () Number of sticks removed on this InteractivePlayer's most recent turn. Returns 0 if this InteractivePlayer has not yet taken a turn. ensure: this.sticksTaken() >= 0 NH-Chapter 9

  39. Interactive player specifications publicvoid setNumberToTake (int number) Set number of sticks this InteractivePlayer takes on its next turn. require: number > 0 publicvoid takeTurn (Pile pile, int maxOnATurn) Take a turn: remove sticks from specified Pile. maxOnATurn is maximum number of sticks a Player can remove on a turn. require: pile.sticks() > 0, maxOnATurn > 0 ensure: 1 <= this.sticksTaken() && this.sticksTaken() <= maxOnATurn && pile.sticks() == old.pile.sticks() - this.sticksTaken() NH-Chapter 9

  40. Interactive player specifications • User interface must also be modified. It creates an InteractivePlayer and a IndependentPlayer : private InteractivePlayer user; private IndependentPlayer computer; public NimTUI () { this.user = new InteractivePlayer("user"); this.computer = new IndependentPlayer("computer"); this.game = null; this.in = new BasicFileReader(); } NH-Chapter 9

  41. Modifying User interface • Added a parameter to playGame indicating whether user wants to play first. private void playGame (int numberOfSticks, boolean userPlaysFirst) { if (userPlaysFirst) game = new Game (user, computer, numberOfSticks); else game = new Game (computer, user, numberOfSticks); while (!game.gameOver()) { game.play(); reportPlay(game.previousPlayer()); } reportWinner(game.winner()); } NH-Chapter 9

  42. User interface – model interaction • How does user interface know when to get a play from user? • user interface checks whose turn it is before invoking play; • Need add a conditional to the play loop, • readNumberToTake is similar to readNumberOfSticks. while (!game.gameOver()) { if (game.nextPlayer().equals(user)) { int numberToTake = readNumberToTake(); user.setNumberToTake(numberToTake); } game.play(); reportPlay(game.previousPlayer()); } NH-Chapter 9

  43. User interface – model interaction • Problem: user interface is more involved in play of the game. • Want “dumb” user interface, as isolated from model as possible. • Role of the user interface is to manage input and output: its knowledge about how the model works should be minimized. • This alternative makes the user interface the model driver. NH-Chapter 9

  44. User interface – model interaction • InteractivePlayer tells user interface it needs a move. • This alternative requires that model be client to user interface. • Don’t want the model dependent on user interface. User interface is properly client to the model. • Common: client needs to know that server has reached some particular state. • User interface (client) needs to know that model (server) has reached a state in which it needs input from the user. NH-Chapter 9

  45. User interface – model interaction • InteractivePlayer must know the user interface. • InteractivePlayer needs to notify an object when it is about to make a move. NH-Chapter 9

  46. Interface InteractiveController interface InteractiveController Models an object that needs to be informed when a InteractivePlayer is about to make a play. publicvoid update (InteractivePlayer player) The specified InteractivePlayer is making a play. NH-Chapter 9

  47. Interface InteractiveController • Before removing sticks from pile, InteractivePlayer notifies InteractiveController by invoking update. publicvoid takeTurn (Pile pile, int maxOnATurn) { controller.update(this); … } NH-Chapter 9

  48. Game InteractivePlayer InteractiveController Pile takeTurn update talkto the user setNumberToTake remove Case: interactive player takes turn NH-Chapter 9

  49. Completing InteractivePlayer • How does the InteractivePlayer know the InteractiveController? • Add one more method to InteractivePlayer: publicvoid register (InteractiveController control) Set InteractiveController this InteractivePlayer is to report to. This InteractivePlayer will notify it before taking its turn. NH-Chapter 9

  50. Class TUIController NH-Chapter 9

More Related