Command pattern encapsulates a request. A command pattern maybe used whenever there is a Sender, Receiver who communicate via a request (let's call it command). Assume, we simulate the game of cricket via a Simulator class which sends commands to the Batsman objects to play certain shots. Each shot is a command given by the simulator to a batsman.
interface Shot{
public void execute();
}
class CoverDrive implements Shot{
private Batsman batter;
public void execute(){
batter.playCoverDrive()
}
}
class straightDrive implements Shot{
private Batsman batter;
public void execute(){
batter.playStraightDrive();
}
}
class Batsman{
def playCoverDrive(){
println("Cover drive")
}
def playStraightDrive(){
println("Cover drive")
}
}
class BatSimulator{
Shot shot
def play(){
shot.execute()
}
}
// main - groovy script start
def sachin = new Batsman()
def command = new CoverDrive(batter : sachin)
def simulator = new BatSimulator(shot : command)
simulator.play()
interface Shot{
public void execute();
}
class CoverDrive implements Shot{
private Batsman batter;
public void execute(){
batter.playCoverDrive()
}
}
class straightDrive implements Shot{
private Batsman batter;
public void execute(){
batter.playStraightDrive();
}
}
class Batsman{
def playCoverDrive(){
println("Cover drive")
}
def playStraightDrive(){
println("Cover drive")
}
}
class BatSimulator{
Shot shot
def play(){
shot.execute()
}
}
// main - groovy script start
def sachin = new Batsman()
def command = new CoverDrive(batter : sachin)
def simulator = new BatSimulator(shot : command)
simulator.play()
0 comments:
Post a Comment