Magazine
 

Creational Design Patterns

public int CalculatePrice() {
int totalPrice = new Italianpizza().price() +
new Coke().price() + new
IceCream().price();
return totalPrice;
}}

This class calculates the total meal and its total price. Here, we have extracted the price calculation and meal package building activity, that is a meal box. The Builder pattern hides the internal details of how the product is built. Since each builder is independent of others therefore it improves modularity and makes the building of other builders easy. Because, each builder builds the final product step by step, we have more control on the final product.

The conclusion is that in Builder Pattern, the client instructs the builder class what it needed and asks for the result, the client is not interested how the builder class will create the objects.

The Prototype Pattern:

This pattern enables you to copy or clone of an existing object instead of creating the new one and may also customized as per the requirement. It copies the existing object to avoid so much overhead. We can also use the clone method by implementing the Clonable interface to create the copy of the existing object.

Benefits: It supports for specifying the new objects with varying structure and varying values, adding and removing products at runtime, dynamically configuring the classes for an application and reducing sub-classing.

 

Usage: These are used when you are not interested in constructing a class hierarchy of factories which is parallel to the class hierarchy of products. Instances of a class can have only one combination of state, the classes are instantiated at run-time.

Example: Let's create an interface and implement it in the various classes.

Shape.java

interface Shape {
public void draw();
}
Square.java
class Square implements Shape {
public void draw() {
System.out.println("square");
}}
Circle.java
class Circle implements Shape {
public void draw() {
System.out.println("circle");
}}Painting.java
class Painting {
public static void main(String[] args) {
Shape s = new Square();
Shape c = new Circle();
paint(s);
paint(c);
}
static void paint(Shape s1) {
s1.draw();
}}

At the runtime, the paint method takes a variable of Shape type and the draw method is called accordingly.

Sept 2007 | Java Jazz Up | 47
 
previous
index
next
 
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,

30
, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 , 54, 55, 56, 57,

58
, 59, 60, 61, 62, 63 , 64, 65 , 66 , 67 , 68 , 69 , 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,   Download PDF