Tuesday, February 13, 2024

Command design pattern

 When to implement ?

Suppose we have a situation ,

There are multiple action to execute based on a single value or criteria. There are several solution to do . We can use if.. else if ladder or switch case to do that  and define the action in each separate method . But if the action feature grow then we need to refactor and transfer the defined action in class . It will we time consuming . So in that situation we can implement Command design pattern like below.

 interface CampaignContactCommand {
        void execute();
    }
    
    class PauseContactCommand implements CampaignContactCommand {

        private ContactHelperNode node;

        public PauseContactCommand(ContactHelperNode node) {
            this.node = node;
        }

        @Override
        public void execute() {
            ContactPauseHelper helper = new ContactPauseHelper(node);
            helper.pauseContact();
            helper.release();
        }
    }
    
    class ResumeContactCommand implements CampaignContactCommand{

        private ContactHelperNode node;
        
        public ResumeContactCommand(ContactHelperNode node) {
            this.node = node;
        }
        
        @Override
        public void execute() {
            ContactResumeHelper helper = new ContactResumeHelper(node);
            helper.resumeContact();
            helper.release();
        }
    }
    
    class UnsubscribeContactCommand implements CampaignContactCommand {

        private ContactHelperNode node;

        public UnsubscribeContactCommand(ContactHelperNode node) {
            this.node = node;
        }

        @Override
        public void execute() {
            ContactUnSubHelper helper = new ContactUnSubHelper(node);
            helper.unSubContact();
            helper.release();
        }
    }
    
    class CampaignContactCommandFactory {
        private ContactHelperNode node;

        public CampaignContactCommandFactory(ContactHelperNode node) {
            this.node = node;
        }

        public CampaignContactCommand createCommand() {

            switch (node.getRequest().getRequestType()) {

            case PAUSE:
                return new PauseContactCommand(node);
            case RESUME:
                return new ResumeContactCommand(node);
            case UNSUB:
                return new UnsubscribeContactCommand(node);
            default:
                return null;
            }
        }
    }

Fluent interface pattern

 public class UserConfigurationManager {     private String userName;     private String password;     private UserConfigurationManager() { ...