Magazine
 

Creational Design Patterns

object is constructed it may exhibit different behavior.

First lets create an interface named Item which contains the two public methods one for packaging the item and other for defining the price of each item.

We are putting all the classes in the package builder.

package builder;

public interface Item {

public Packing pack();

public int price();

}

Now, we define the classes for each of the item, as pizza, ice cream and cold drink. All these classes will implement the Item interface.

Lets start with Pizza. Here we are making the pizza.java class as abstract because we will implement price method according the type of the pizza. A pizza is wrapped in the paper and is served. The class Wrapper is sub-class of Packing interface.
Lets start with Pizza. Here we are making the pizza.java class as abstract because we will implement price method according the type of the pizza. A pizza is wrapped in the paper and is served. The class Wrapper is sub-class of Packing interface.

Lets consider this class as Pizza.java:

package builder;
public abstract class Pizza implements
Item {
public Packing pack() {
return new Wrapper();
}
public abstract int price();
}

 

Lets consider this class as Pizza.java:

package builder;
public abstract class Pizza implements
Item {
public Packing pack() {
return new Wrapper();
}
public abstract int price();
}

Now the class pizza further extended to Italianpizza, Cheesepizza etc. All these classes will implement the price() method and return a price for each type of pizza. In this example we are implementing the Italianpizza class of the Pizza class.

Italianpizza.java

package builder;
public class Italianpizza extends Pizza
{
public int price() {
return 200;
}
}

Now lets consider the item Ice Cream

IceCream.java
package builder;
public class IceCream
implements Item {
public Packing pack() {
return new Envelop();
}
public int price() {
return 20;
}}

Now, let’s see the Builder class, MealBuilder. This is the class which serves the meal.

package builder;
public class MealBuilder {
public Packing additems() {
Item[] items = {new Italianpizza(),
new IceCream(), new Coke()}
return new MealBox().
addItems(items);
}

Sept 2007 | Java Jazz Up | 46
 
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