命令(Command)模式例子2

命令(Command)模式例子2 -------- AudioPlayer系统

 

系统描述: 小女孩julia有一个盒式录音机,有播音play,倒带rewind,停止stop功能。julia不需要知道命令的执行细节,只需要知道在键盘上按下什么键就可以了。 用命令模式来模拟。

 

代码:

/**
 *  This class plays the role of Abstract Command
 */

public interface Command
{
	public abstract void execute ( );
}

 

/**
 *  This class plays the role of Concrete Command
 */

public class PlayCommand implements Command
{
	private AudioPlayer myAudio;

	public PlayCommand ( AudioPlayer a)
    {
		myAudio = a;
	}

	public void execute( )
    {
		myAudio.play();
	}
}

 

/**
 *  This class plays the role of Concrete Command
 */

public class RewindCommand implements Command
{
	private AudioPlayer myAudio;

	public RewindCommand ( AudioPlayer a)
    {
	    myAudio = a;
	}
	public void execute()
    {
	    myAudio.rewind();
	}
}

 

/**
 *  This class plays the role of Concrete Command
 */

public class StopCommand implements Command
{
    /**
     * @directed 
     */
    private AudioPlayer myAudio;
	
	public StopCommand ( AudioPlayer a)
    {
		myAudio = a;
	}
	public void execute( )
    {
		myAudio.stop();
	}
}

 

/**
 * 	This is the Invoker role
 */
public class Keypad
{
    /**
     * @link aggregation 
     */
	private Command playCmd;

    /**
     * @link aggregation 
     */
    private Command rewindCmd;

    /**
     * @link aggregation 
     */
    private Command stopCmd;
	
	public Keypad(Command play, Command stop, Command rewind)
	{
        // concrete Command registers itself with the invoker
		playCmd = play;
		stopCmd = stop;
        rewindCmd = rewind;
	}
	public void play()
	{
		playCmd.execute();
	}
	public void stop()
	{
		stopCmd.execute();
	}
    public void rewind()
    {
        rewindCmd.execute();
    }
}

 

/**
 *  This class plays the role of Receiver
 */

public class AudioPlayer
{
	public void play( )
	{
		System.out.println("Playing...");
	}

	public void rewind( )
	{
		System.out.println("Rewinding...");
	}
	
	public void stop()
	{
		System.out.println("Stopped.");
	}                                                                    
}

 

/**
 * 	This is the Client role
 */
public class Julia
{
    /**
     * @link aggregation 
     */
    private static Keypad keypad ;

    /**
     * @link aggregation 
     */
    private static AudioPlayer myAudio = new AudioPlayer();

	public static void main(String[] args)
	{
    	test1();
	}

    private static void test1()
    {
    	Command play = new PlayCommand(myAudio);
        Command stop = new StopCommand(myAudio);
        Command rewind = new RewindCommand(myAudio);

        keypad = new Keypad(play, stop, rewind);

        keypad.play();
        keypad.stop();
        keypad.rewind();

        keypad.stop();
        keypad.play();
        keypad.stop();
    }
}               

 

你可能感兴趣的:(命令模式)