5. Prototypes Design Pattern
Prototypes Design Pattern
- Prototype pattern is one of the Creational Design patterns, so it provides a mechanism of object creation. However, Prototype pattern is used when the Object creation is a costly affair. Also, it requires a lot of time and resources and if you have a similar object already existing. Therefore, this pattern provides a mechanism to copy the original object to a new object and then modify it according to our needs. Moreover, this pattern uses java cloning to copy the object.
- The concept is to copy an existing object rather than creating a new instance from scratch.bcoz creating new object may be constly.
- This approach saves costly resource and time, especially when object creation is a heavy process.
- Imagine you have an object, let's call it "Prototype". This object is quite complex, and you want to make copies of it, but creating each copy from scratch would be inefficient and time-consuming. So, instead of creating copies by re-creating the whole object every time, you create a prototype, which is essentially a blueprint or template of the original object.
Here's how it works:
1. You start by creating your original object, the prototype.
2. When you need a copy, instead of creating a new object and setting all its properties again, you simply clone the prototype.
3. The clone operation creates a new object with the same properties as the prototype
Object Cloning
The Prototype Pattern works on the Cloning concept. However, in Java, if you’d like to use cloning, you can utilize the clone () method and the Cloneable interface. By default, clone () performs a shallow copy. Moreover, Serializable can be used to simplify deep copying.
Program :
import java.lang.reflect.Constructor;
class Bike implements Cloneable
{
private String name;
public Bike(String name)
{
this.name = name;
}
public void getBike() throws Exception
{
this.name = "Bike Name is " ;
Thread.sleep(6000);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return this.name;
}
}
public class Prototype {
public static void main(String[] args) throws Exception {
Bike b1 = new Bike("Shine");
// b1.getBike();
System.out.println(b1.getName());
Bike b2 = (Bike) b1.clone();
System.out.println(b2.getName());
b2.setName("Hero Honda");
System.out.println("After setting copy Object : "+b2);
}
}
// output
Shine
Shine
After setting copy Object : Hero Honda
Comments
Post a Comment