Showing posts with label design pattern. Show all posts
Showing posts with label design pattern. Show all posts

Tuesday, November 5, 2024

Fluent interface pattern

 public class UserConfigurationManager {
    private String userName;
    private String password;
    private UserConfigurationManager() {
    }
    public UserConfigurationManager setUserName(String userName) {
        this.userName = userName;
        return this;
    }
    public UserConfigurationManager setPassword(String password) {
        this.password = password;
        return this;
    }
    public static UserConfigurationManager make(Consumer<UserConfigurationManager> consumer) {
        System.out.println("making configuration..........");
        UserConfigurationManager configurationManager = new UserConfigurationManager();
        consumer.accept(configurationManager);
        return configurationManager;
    }
}

public class MainApp {
    public static void main(String[] args) {
        UserConfigurationManager.make(configManager -> configManager.setUserName("lokman").setPassword("12345"));
    }

Note: Fluent pattern can be used to define Model in JPA

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;
            }
        }
    }

Tuesday, November 21, 2023

Chain Responsibility design pattern

 Chain Responsibility design pattern:

Chain responsibility design pattern is a behavioral design pattern . We will implement this design pattern to achieve loose coupling in software where several operation will execute one by one with same request . 

In this design pattern same request is pass through the chain until finish all the task in the chain .

Senarios: - Suppose we want to build an Notification sender application . That can notify user / developer through sms/ email etc . So we can create a class Notify user class and can implement message send logic there .  But in those logic there should have some other logic such as - loading credential information form db etc.

Another thing- in future we want to send notification to other , so respective service should execute one by one . If we don't follow a structured way and code base grows it will difficult to handle and need more refactoring .

So , we can create a chain of responsibility and execute one by one .

One service execute its work and can pass request to the next service in the chain .

Lets see the example of chain responsibility design pattern below-

1. Create an abstract class. Every service will override its execute method with same request

 AbstractService

public abstract class AbstractService {

    private AbstractService next;

    /**
     * Build the chain of objects
     */
    public static synchronized AbstractService link(AbstractService first, AbstractService... chain) {
        AbstractService head = first;
        for (AbstractService nextChain : chain) {
            head.next = nextChain;
            head = nextChain;
        }
        return first;
    }

    /**
     * Subclasses will implement this method with concrete checks.
     */
    public abstract Request execute(Request request);

    /**
     * Runs check on the next object in chain or ends traversing if we're in last in
     * the chain
     */
    protected Request executeNext(Request request) {
        if (next == null)
            return request;
        return next.executeNext(request);
    }

}

 Request:

public class Request {

    private String title;

    public void setTitile(String title) {
        this.title = title;
    }
}

AdminNotifyService:

public class AdminNotifyService extends AbstractService{

    @Override
    public Request execute(Request request) {
       
        System.out.println("AdminNotifyService.........");
       
        return executeNext(request);
    }
}

UserNotifyService:

public class UserNotifyService extends AbstractService{

    @Override
    public Request execute(Request request) {
       
        System.out.println("UserNotifyService.......");
       
        return executeNext(request);
    }
}

 MainApp:

public class MainApp {

    public static void main(String[] args) {
       
        Request request = new Request();
        request.setTitile("chain responsibility");
       
        AbstractService abstractService = AbstractService.link(new AdminNotifyService(), new UserNotifyService());
        abstractService.execute(request);
    }
}

Sunday, February 13, 2022

Composite design pattern

 Composite design pattern is the part of structural design pattern .

When we need a composite object what will maintain a tree structure then we can use composite design pattern .

let's see an example . We want to develop our company organogram -

Project managers and sales managers works under the CTO.  Developer works under the Project managers. Sales persons works under the sales manager.

public class Employee {

private String name;

private String department;

private int salary;

List<Employee> suborddinates;

public Employee(String name, String department, int salary) {

this.name = name;

this.department = department;

this.salary = salary;

suborddinates = new ArrayList<Employee>();

}

public void addSubordinates(Employee employee) {

suborddinates.add(employee);

}

public List<Employee> getSubordinates() {

return suborddinates;

}

@Override

public String toString() {

return "Employee [name=" + name + ", department=" + department + ", salary=" + salary + "]";

}


//Main class

public class MainApp {

public static void main(String[] args) {

Employee cto = new Employee("msr", "CTO", 100000);

Employee salesManager = new Employee("Hera", "Sales Manager", 80000);

Employee productManager = new Employee("Shahin", "Product Manager", 80000);

Employee sales1 = new Employee("makku", "Sales", 10000);

Employee sales2 = new Employee("Rumana", "Sales", 20000);

Employee dev1 = new Employee("lokman", "Developer", 60000);

Employee dev2 = new Employee("Sahabur", "Developer", 60000);


cto.addSubordinates(productManager);

cto.addSubordinates(salesManager);


productManager.addSubordinates(dev1);

productManager.addSubordinates(dev2);


salesManager.addSubordinates(sales2);

salesManager.addSubordinates(sales1);


System.out.println(cto.toString());

for (Employee manager : cto.getSubordinates()) {

System.out.println(manager.toString());

for (Employee junior : manager.getSubordinates()) {

System.out.println(junior.toString());

}

}

//output

Employee [name=msr, department=CTO, salary=100000]

Employee [name=Shahin, department=Product Manager, salary=80000]

Employee [name=lokman, department=Developer, salary=60000]

Employee [name=Sahabur, department=Developer, salary=60000]

Employee [name=Hera, department=Sales Manager, salary=80000]

Employee [name=Rumana, department=Sales, salary=20000]

Employee [name=makku, department=Sales, salary=10000]

Element of a good table (Ref: Database design mere mortals by Michael J. Hernandez)

  Elements of the Ideal Table: It represents a single subject, which can be an object or event that reduces the risk of potential data integ...