Core Java

Design Patterns: Prototype

The one of creational design patterns is a Prototype design pattern. Despite that the Prototype is the creational pattern it distinguishes from other patterns by a concept. I mean that the Prototype in some sense creates itself. I’m going to explain it bellow.java-design-patterns

All magic of the Prototype pattern is based on a clone() method of a java Object. So let’s to consider an example of usage and then I will try to figure out which cons and pros this pattern has.
 
 
prototype-design-pattern-java

The class diagram above shows to us an basic sense of the pattern. An abstract class or an interface can play role of a prototype. Notice that the prototype have to extend Cloneable interface. That’s because concrete implementations of the prototype will invoke the clone() method. The particular class which implements interface (extends the abstract class) has to contain method which will return a copy of itself with the help of clone operation.

In my example I declared the Unicellular interface as the prototype and the Amoeba class as its realisation:

public interface Unicellular extends Cloneable {

	public Unicellular reproduce();

}
public class Amoeba implements Unicellular {

	public Unicellular reproduce() {
		Unicellular amoeba = null;
		try {
			amoeba = (Unicellular) super.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return amoeba;
	}

	public String toString() {
		return "Bla bla bla it's a new amoeba...";
	}

}

Demonstration:

...
	public static void main(String[] args) {

		Unicellular amoeba = new Amoeba();

		List< Unicellular > amoebaList = new ArrayList< Unicellular >();

		amoebaList.add(amoeba.reproduce());
		amoebaList.add(amoeba.reproduce());
		amoebaList.add(amoeba.reproduce());

		for (Unicellular a : amoebaList)
			System.out.println(a);

	}
...

The result:

Bla bla bla it’s a new amoeba…
Bla bla bla it’s a new amoeba…
Bla bla bla it’s a new amoeba…

What about the cons and pros? Actually I don’t know what to say regarding this, because I have never encountered such situations where the Prototype pattern will be applied appropriately. Maybe in some cases when you don’t need to call a constructor explicitly or when a system don’t need to depend on way of objects creation.
 

Reference: Design Patterns: Prototype from our JCG partner Alexey Zvolinskiy at the Fruzenshtein’s notes blog.

Alexey Zvolinskiy

Alexey is a test developer with solid experience in automation of web-applications using Java, TestNG and Selenium. He is so much into QA that even after work he provides training courses for junior QA engineers.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button