Pin It

How to implement Prototype Design Pattern in Java ?.

Program to demonstrate how to implement Prototype Design Pattern in Java.

package com.hubberspot.designpattern.creational.prototype;

// 1. Create a class Dog implementing Cloneable
// interface
public class Dog implements Cloneable {

    // 2. Create few properties to Dog object.
    private String name;
    private String breed;

    // 3. Create a constructor for properties
    // initialization
    public Dog(String name, String breed) {
        super();
        this.name = name;
        this.breed = breed;
    }

    // 4. Create getters and setters for the properties
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getBreed() {
        return breed;
    }

    public void setBreed(String breed) {
        this.breed = breed;
    }

    // 5. Create a method which will create a
    // prototype or clone of the object invoking
    // this method
    public Dog makeCopyOfDog() {

        Dog clonedDog = null;

        // 6. super.clone() returns clone of the object
        // invoking it.
        try {
            clonedDog = (Dog) super.clone();
        } catch (CloneNotSupportedException e) {

            e.printStackTrace();
        }
        return clonedDog;
    }



    public static void main(String[] args) {

        // 7. Create a original dog
        Dog originalDog = new Dog("Jimmy" , "Bulldog"); 

        // 8. Create clone of dog created in step 7 by calling
        // originalDog.makeCopyOfDog() method
        Dog clonedDog = originalDog.makeCopyOfDog();

        System.out.println("Original Dog's name is: " + originalDog.getName());
        System.out.println("Original Dog's breed is: " + originalDog.getBreed());
        System.out.println();
        System.out.println("Cloned Dog's name is: " + clonedDog.getName());
        System.out.println("Cloned Dog's breed is: " + clonedDog.getBreed());

    } 

}



Output of the program :


Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot