{{theTime}}

Search This Blog

Total Pageviews

Command Design Pattern

/** Sample Command Design Pattern Implementation for TV Remote Commands */

public class CommandDesignPattern
{
   
    interface Command {
        void execute() ;
    }
   
    class TV {
       
        public TV() {
           
        }
        public void turnOn(){
            System.out.println("TV ON") ;
        }
       
        public void turnOff(){
            System.out.println("TV OFF") ;
        }
    }
   
    class Remote {      
        public void execute(Command command){
            command.execute() ;
        }
    }
   
    class OnTVCommand implements Command {
        TV tv ;      
        public OnTVCommand(TV tv){
            this.tv = tv ;
        }

        @Override
        public void execute()
        {
            tv.turnOn() ;
        }
    }
   
    class OffTVCommand implements Command {      
        TV tv ;
        public OffTVCommand(TV tv){
            this.tv = tv ;
        }

        @Override
        public void execute()
        {
            tv.turnOff() ;
        }
    }
    public static void main(String[] str) {      
        performRemote(str) ;      
    }
   
    private static void performRemote(String[] str)
    {
        CommandDesignPattern pattern = new CommandDesignPattern() ;
        TV tv = pattern.new TV() ;
        Command onTv = pattern.new OnTVCommand(tv) ;
        Command offTv = pattern.new OffTVCommand(tv) ;
        Remote remote = pattern.new Remote() ;
        String commandname = "ON" ;
        if(null != str && str.length>=1){
            commandname = str[0] ;
        }
        switch(commandname) {
        case "ON" :
            remote.execute(onTv) ;
            break ;
        case "OFF" :
            remote.execute(offTv) ;
            break ;
         default:
                 System.out.println("No TV Commands") ;
        }
    }
}

No comments:

Java Sequenced Collection Java Sequenced Collection The Sequenced Collection feature was introduced in Jav...