Chapter 9 : Interface - PowerPoint PPT Presentation

1 / 49
About This Presentation
Title:

Chapter 9 : Interface

Description:

public Game (Player player1, Player player2, int sticks) ... In a Maze game. Chapter 9. 25. Multiple Inheritance. Weapon. Pen 'interface' MissileLauncher ... – PowerPoint PPT presentation

Number of Views:35
Avg rating:3.0/5.0
Slides: 50
Provided by: Empl154
Category:
Tags: chapter | game | interface | maze

less

Transcript and Presenter's Notes

Title: Chapter 9 : Interface


1
Chapter 9 Interface
2
Objectives
  • the role of abstraction in the specification of a
    server
  • 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.
  • be able to use an interface to capture
    commonality among similar classes.

3
Class Player (Chapter 8)
Class Player private String name
private int sticksTaken public Player
(String name) this.name name this.sticksTak
en 0 public String name ()
return name public int
sticksTaken () return sticksTaken
public void takeTurn (Pile pile, int maxOnTurn)
pile.remove(1) sticksTaken 1
4
Class Game
  • class Game
  • private static final int MAX_ON_A_TURN 3
  • private Player player1, player2, nextPlayer,
    previousPlayer
  • private Pile pile
  • public Game (Player player1, Player
    player2, int sticks)
  • assert sticks gt 0 "precondition initial
    sticks gt 0"
  • this.player1 player1, this.player2 player2
  • this.nextPlayer player1, this.previousPlayer
    null
  • this.pile new Pile(sticks)
  • public int sticksLeft ()
  • return pile.sticks()
  • public Player nextPlayer () return
    nextPlayer
  • public Player previousPlayer () return
    previousPlayer
  • public boolean gameOver () return
    pile.sticks() 0
  • public Player winner ()
  • if (gameOver())
  • return otherPlayer(previousPlayer)

5
Class Game
  • public void play ()
  • if (!gameOver())
  • nextPlayer.takeTurn(pile,MAX_ON_A_TURN)
  • previousPlayer nextPlayer
  • nextPlayer otherPlayer(nextPlayer)
  • public String toString ()
  • return "Game with players " player1 ", and
    player2
  • private Player otherPlayer (Player player)
  • if (player player1)
  • return player2
  • else
  • return player1
  • //end of Game implementation

6
Modeling alternative implementations
  • There are several strategies a Player may use.
  • Then, we have to choose the kinds of players to
    use when we start the game!

class public NimTUI public NimTUI ()
this.player1 new TimidPlayer("Player1")
this.player2 new CleverPlayer("Player2
") this.game null
this.in new Scanner(System.in)
What else needs to be changed?
7
Modeling alternative implementations
  • What else need to be changed?
  • If there are three different player classes, we
    need modify all of them to handle all possible
    combination!
  • Lets use an abstraction for 3 player classes!

8
Abstraction
  • An abstraction consists of the common
    specifications (interfaces).
  • Abstraction is common in life

9
Player Abstraction
  • Player abstraction should be

10
Java interfaces
  • A Java interface is used to specify minimal
    functionality that a client requires of a server.
  • A Java interface contains
  • A Java interface does not contain

interface Player public String name
() public int sticksTaken () public void
takeTurn (Pile pile, int maxOnATurn)
11
Java interface implementation
  • A class implements an interface by including
    definitions for all methods in the interface.
  • You can not instantiate an interface

class TimidPlayer implements Player public
String name () public int sticksTaken ()
public void takeTurn (Pile pile, int
maxOnATurn)
12
Java interface
  • Interface Player abstracts

13
Interface and types
  • An interface defines a type.
  • The type TimidPlayer is said to be a subtype of
    the type Player.
  • The type Player is a supertype of type TimidPlayer

14
Rewriting Game
  • We can use previous Game,
  • if Player is an interface and not a class.

private Player player1, player2
  • Constructors and methods can have Player
    parameters

public Game (Player player1, Player player2, int
sticks)
  • Queries can return values of type Player

public Player nextPlayer ()
15
Rewriting Game
  • The Game will be instantiated

player1 new TimidPlayer(Wakko) player2 new
CleverPlayer(Yakko) Game game new
Game(player1, player2, 3)
  • We may later change our game strategy as

player1 new GreedyPlayer(Guy) player2 new
TimidPlayer(Sis) Game game new Game(player1,
player2, 3)
16
Types and Subtypes
  • Subtype rules if type A is a subtype of type B,
    then
  • If a value of type Player is expected, a value of
    any Player subtype can be provided.

17
Static types
  • The Game method nextPlayer() is specified as

public Player nextPlayer () The Player whose turn
is next.
  • If game is a Game instance, Player is the static
    type of expression

game.nextPlayer()
  • Because the type of game.nextPlayer() can be
    determined by the compiler from the program text.

18
Dynamic types
  • But, when game.nextPlayer() is evaluated during
    execution, value returned will reference an
    specific object
  • The dynamic type is always a subtype of Player.

19
Types and Subtypes
private Player nextPlayer private void
reportPlay (Player player) public Player winner
() return Player expression
  • Value of the subtype of type Player can be used

TimidPlayer timid new TimidPlayer("Wakko") next
Player timid reportPlay(timid) public Player
winner () return timid
20
Types and Subtypes
  • If game is a Game instance, we cannot write the
    following

TimidPlayer next game.nextPlayer()
  • Assignment operator requires a TimidPlayer on
    the right.

21
Types and Subtypes
  • Player p1, p2
  • TimidPlayer tp new TimidPlayer("Wakko")
  • CleverPlayer cp new CleverPlayer("Guy")

p1 tp
p2 cp
p2 p1
22
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
23
Revised Nim game
  • Classes Pile and Game remain the same.
  • Game constructors, methods, and instance
    variables are written in terms of type Player.
  • NimTUI still has instance variables of type
    Player
  • private Player player1, player2
  • public NimTUI ()
  • this.player1 new TimidPlayer("Player1")
  • this.player2 new GreedyPlayer("Player2")
  • this.game null
  • this.in new BasicFileReader()

24
Revised Nim game
Views, controls
directs
2
views
2
25
Example Interface Movable
  • In a Maze game

26
Multiple Inheritance
  • An Explorer wields a weapon
  • Multiple inheritance

27
Multiple inheritance of interfaces
class Sword implements Weapon, Movable
28
Interface extension
  • Assume all weapons are movable

interface Weapon extends Movable
29
Extending multiple interfaces
  • An interface can extend more than one interface.

interface DataIO extends DataInput, DataOutput

30
Nim user vs. computer
  • The same simple Nim game and text-based user
    interface. User plays against the computer.
  • On the users turn, the user will be prompted for
    the number of sticks to take

Enter the number denoting the action to perform
Run game...............1 Exit...................2
Enter choice 1 Enter number of sticks (a
positive integer) 5 User plays first? (Key yes
or no) yes Enter number to take (a positive
integer, at most 3) 3 Player user takes 3
stick(s), leaving 2. Player computer takes 1
stick(s), leaving 1. Player computer wins.
31
Nim user vs. computer
  • Define two classes IndependentPlayer (computer),
    and InteractivePlayer (user).

32
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 InteractivePlayers name.
  • public int 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() gt 0
  • public void setNumberToTake (int number)
  • Set number of sticks this InteractivePlayer
    takes on its next turn.
  • require number gt 0
  • public void 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() gt 0, maxOnATurn gt
    0
  • ensure 1 lt this.sticksTaken()
    this.sticksTaken() lt maxOnATurn
  • pile.sticks() old.pile.sticks() -
    this.sticksTaken()

33
Interactive player specifications
  • The interface NimTUI 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.in new BasicFileReader()
this.game null
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())
34
User interface model interaction
  • How does user interface know when to get a play
    from user?
  • Need add a conditional to the play loop,

while (!game.gameOver()) if
(game.nextPlayer().equals(user)) int
numberToTake readNumberToTake() user.setNumbe
rToTake(numberToTake)
game.play() reportPlay(game.previousPlayer(
))
  • readNumberToTake is similar to readNumberOfSticks.

35
User interface model interaction
  • Problem user interface is more involved in play
    of the game.
  • Want a dumb user interface, as isolated from
    model as possible.

36
Case interactive player takes turn
InteractiveController
Pile
InteractivePlayer
Game
takeTurn
talk to the user
setNumberToTake
remove
37
User interface model interaction
  • InteractivePlayer tells the user interface it
    needs a move.
  • InteractivePlayer must know the user interface.

interface InteractiveController Models an object
that needs to be informed when a
InteractivePlayer is about to make a play.
public void update (InteractivePlayer player)
The specified InteractivePlayer is making a
play. Class InteractivePlayer implements Player
private InteractiveController controller
public void takeTurn (Pile pile, int
maxOnATurn) controller.update(this
)
38
Case interactive player takes turn
39
Completing InteractivePlayer
  • How does the InteractivePlayer know the
    InteractiveController?

class InteractivePlayer implements Player
public void register (InteractiveController
control) Set InteractiveController this
InteractivePlayer is to report to. This
InteractivePlayer will notify it before taking
its turn.
40
Class TUIController
  • Design a new class TUIController
  • TUIController will get moves from the user, give
    them to a InteractivePlayer

41
TUIController and Game
  • TUIController must know maximum number of sticks
    that can be removed on users turn.
  • Add the following method to the Game

class Game public int maxOnThisTurn ()
if (pile.sticks() lt MAX_ON_A_TURN)
return pile.sticks() else return
MAX_ON_A_TURN
42
NimTUI playGame
  • TUIController is created by the NimTUI when Game
    is created

class NimTUI private void playGame (int
numberOfSticks, boolean userPlaysFirst) if
(userPlaysFirst) game new Game (user,
computer, numberOfSticks) else
game new Game (computer, user,
numberOfSticks) new TUIController(user,ga
me,in) while (!game.gameOver())
game.play() reportPlay(game.previousPlaye
r()) reportWinner(game.winner())
43
The strategy pattern
  • There are duplicated code in player classes,
    TimidPlayer, GreedPlayer, CleverPlayer.
  • To reduce,

44
Strategy pattern
  • PlayStrategy is an interface that can be
    implemented in various ways.
  • PlayerWithstrategy is a composite object.

45
Strategy pattern
  • PlayerWithStrategy has an instance variable
    referencing a PlayStrategy.
  • takeTurn() determines of sticks to take to
    PlayStrategy.
  • setStrategy() allows a Players strategy to be
    changed after the Player is instantiated

class PlayerWithStrategy private
PlayStrategy strategy public void takeTurn
(Pile pile, int maxOnATurn) int number
strategy.numberToTake(pile, maxOnATurn) pile.rem
ove(number) sticksTaken number
public void setStrategy (PlayStrategy strategy)
this.strategy strategy
46
Strategy pattern
  • PlayStrategy is an interface that can be
    implemented in various ways.

interface PlayStrategy public int numberToTake
(Pile pile, int maxOnATurn)
  • We can implement TimidStrategy as

class TimidStrategy implements PlayStrategy
public void numberToTake (Pile pile, int
maxOnATurn) return 1
47
Casting
Player player InteractivePlayer user new
InteractivePlayer("Louis") player user
//legal user player // not legal.
  • If we are certain of the dynamic type of a
    value, we can cast the expression to this type

user (InteractivePlayer) player
Player player InteractivePlayer user new
InteractivePlayer("Louis") player user
//legal user (InteractivePlayer) player //
legal.
48
Boolean operator instanceOf
  • Boolean operator instanceof is used to
    determined the type of value an expression
    produces at run-time.

expression instanceof type
  • Returns true if the variable player references
    an InteractivePlayer when the expression is
    evaluated.

player instanceof InteractivePlayer
49
Summary
  • Fundamental notion of interface
  • Subtyping
Write a Comment
User Comments (0)
About PowerShow.com