Monday, 30 July 2018

Redis vs Memcached

One major difference is that Memcache has an upper memory limit at all times, while Redis does not by default (but can be configured to). If you would always like to store a key/value for certain amount of time (and never evict it because of low memory) you want to go with Redis. Of course, you also risk the issue of running out of memory

======================================================================

Memcached is good at being a simple key/value store and is good at doing key => STRING. This makes it really good for session storage.
Redis is good at doing key => SOME_OBJECT.
=======================================================================




Prototype pattern

Prototype pattern can be achieved by deep cloning of an object.

For example:
Problem:
1) I have invoked the DB for an employee details, assign the object to X reference
2) I need one more object of the same employee, we can reuse the X reference, like Employee Y = X;
3) But there is a problem here. If any value is changed in X reference, that will get reflected on Y reference as well.

Problem:
To avoid this, we need to invoke the DB again at step 2, that would be an expensive call.

Solution:
To avoid all these issues, we can go with an Deep Cloning of an Employee object. Hence we are creating a prototype of an X object.

Employee Y = X.clone();

If we use Shallow Cloning, we may not get values of the inner most objects. 
For example, Empoyee ==> Address details.

To achieve this, we need to go with Deep cloning. 

Builder Pattern

We can build the object as per our convenience, 
there is no hard rule to pass certain amount of parameters.

For example, if we have a constructor with 3 parameters, 
and if we need to create an object, 
we need to pass the values to the constructors even if we don't know what is age. 

To avoid it, we can use Builder pattern. 
Where we can build the object based on the values we have.

public class Employee {
    private String empname;
    private String age;
    private String department;

    public String getEmpname() {
        return empname;
    }

    public Employee setEmpname(String empname) {
        this.empname = empname;
        return this;
    }

    public String getAge() {
        return age;
    }

    public Employee setAge(String age) {
        this.age = age;
        return this;
    }

    public String getDepartment() {
        return department;
    }

    public Employee setDepartment(String department) {
        this.department = department;
        return this;
    }
}

public class EmployeeTest {
    public static void main(String[] args) {
        Employee emp = new Employee();
        emp.setAge("10").setDepartment("IT").setEmpname("Doll");

        System.out.println(emp.getDepartment());
    }
}