Monday 30 July 2018

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. 

No comments:

Post a Comment