{{theTime}}

Search This Blog

Total Pageviews

Command Design Pattern Java Implementation

Sample Java Command design pattern implementation to develop TV Remote Application.


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:

Cucumber Eclipse sample program

Cucumber Eclipse SetupCreate Eclipse Maven Project Open pom.xml Goto Dependencies Add GroupId: info.cukes, Artifact Id: cucumber-java, Versi...