Title: Chapter 9 : Interface
1Chapter 9 Interface
2Objectives
- 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.
3Class 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
4Class 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)
5Class 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
6Modeling 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?
7Modeling 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!
8Abstraction
- An abstraction consists of the common
specifications (interfaces). - Abstraction is common in life
9Player Abstraction
- Player abstraction should be
10Java 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)
11Java 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)
12Java interface
- Interface Player abstracts
-
13Interface 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
14Rewriting 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 ()
15Rewriting 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)
16Types 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.
17Static 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.
18Dynamic 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.
19Types 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
20Types 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.
21Types and Subtypes
- Player p1, p2
- TimidPlayer tp new TimidPlayer("Wakko")
- CleverPlayer cp new CleverPlayer("Guy")
p1 tp
p2 cp
p2 p1
22Types 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
23Revised 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()
24Revised Nim game
Views, controls
directs
2
views
2
25Example Interface Movable
26Multiple Inheritance
- An Explorer wields a weapon
- Multiple inheritance
27Multiple inheritance of interfaces
class Sword implements Weapon, Movable
28Interface extension
- Assume all weapons are movable
interface Weapon extends Movable
29Extending multiple interfaces
- An interface can extend more than one interface.
interface DataIO extends DataInput, DataOutput
30Nim 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.
31Nim user vs. computer
- Define two classes IndependentPlayer (computer),
and InteractivePlayer (user).
32Interactive 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()
33Interactive 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())
34User 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.
35User 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.
36Case interactive player takes turn
InteractiveController
Pile
InteractivePlayer
Game
takeTurn
talk to the user
setNumberToTake
remove
37User 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
)
38Case interactive player takes turn
39Completing 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.
40Class TUIController
- Design a new class TUIController
-
- TUIController will get moves from the user, give
them to a InteractivePlayer
41TUIController 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
42NimTUI 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())
43The strategy pattern
- There are duplicated code in player classes,
TimidPlayer, GreedPlayer, CleverPlayer. -
- To reduce,
44Strategy pattern
- PlayStrategy is an interface that can be
implemented in various ways. - PlayerWithstrategy is a composite object.
45Strategy 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
46Strategy 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
47Casting
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.
48Boolean 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
49Summary
- Fundamental notion of interface
-
- Subtyping