Head first design mode 1 command mode

Source: Internet
Author: User

Command mode

Through the command mode, the requested object and the requested object can depend on abstract programming rather than specific classes to achieve decoupling. In addition, the command mode can be revoked because the request is well encapsulated.

package command;interface ICommand{    public void excute();    public void undo();}class Light{    private String mName;    public Light(String name){        mName=name;    }    public void on(){        System.out.println(mName+" on");    }    public void off(){        System.out.println(mName+" off");    }}class LightOnCmd implements ICommand{    Light mLight;    public LightOnCmd(Light l){        mLight=l;    }        @Override    public void excute() {        // TODO Auto-generated method stub        mLight.on();    }    @Override    public void undo() {        // TODO Auto-generated method stub        mLight.off();    }    }class LightOffCmd implements ICommand{    Light mLight;    public LightOffCmd(Light l){        mLight=l;    }        @Override    public void excute() {        // TODO Auto-generated method stub        mLight.off();    }    @Override    public void undo() {        // TODO Auto-generated method stub        mLight.on();    }    }class LightController{    ICommand mCmd;    public void setCommand(ICommand cmd){        mCmd=cmd;    }        public void press(){        if(mCmd!=null){            mCmd.excute();        }    }}public class CommandPattern {    /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub        Light light=new Light("Bedroom Light");        LightOnCmd lightOnCmd=new LightOnCmd(light);        LightOffCmd lightOffCmd=new LightOffCmd(light);        LightController lightController=new LightController();        lightController.setCommand(lightOnCmd);        lightController.press();        lightController.setCommand(lightOffCmd);        lightController.press();    }}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.