Sei sulla pagina 1di 24

Design patterns - Creational

By Srinivas

Short description of Design Patterns - Creational Patterns

Introduction to Design Patterns.


Also covers, who implemented them first.
Uses of Design Patterns.
Types of Design Patterns.
Covers the Creational Design Patterns.

@2016 Attune World Wide All right reserved.


www.attuneww.com
Contents
Preface
About This Guide
Intended Audience
Revision History
Design patterns - Introduction
What is Gang of Four (GOF)?
Usage of Design Patterns
Best Practices
Common platform for developers
Types of Design Patterns
Creational Patterns
Structural Patterns
Behavioral Patterns
Creational Design Patterns
Design Pattern - Singleton Pattern
Implementation Steps
Design Patterns - Builder Pattern
Implementation Steps
Design Patterns - Prototype Pattern
Implementation Steps
Conclusion

Design Patterns Last Updated: November 2016 | Page 2 of 24


Preface

About This Guide


This guide will help the the developer or individual, who wants to get the brief overview
of Design patterns - Creational Patterns. We are going to see brief introduction about
them, and we will discuss about them theoretically and programmatically about them.

Intended Audience
This guide is particularly intended for the developers who want to gain knowledge and
insight into Design Patterns - Creational Patterns. The developers or audience must be
having knowledge of the Core Java.

Revision History
This document is the first version of document which is going to cover regarding the
topics of Design Patterns - Creational Patterns.

Design Patterns Last Updated: November 2016 | Page 3 of 24


Design patterns - Introduction
Design patterns signifies the most best practices which have been used by object-
oriented software developers. Design patterns are a great solution for the problems that
developers may face when they are developing the software.

These solutions have been obtained by trial and error by various software developers for
quite a substantial period of time.In software engineering, we can say that a design
pattern can be said as a general repeatable solution for any normally occurring problem
in terms of software design.

A design pattern cannot be said as a finished design which can be transformed directly
into some code. This can be said as a description or template for how solving any
problem which can be used in various scenarios.

What is Gang of Four (GOF)?


In 1994, four authors Richard Helm, Erich Gamma, John Vlissides, and Ralph Johnson
published a book titled Design Patterns - Elements of Reusable Object-Oriented
Software which has initiated Design Patterns in Software development.

These authors have been called as Gang of Four (GOF) from then. According to these
authors, design patterns have been primarily based on the below principles of object
orientated design.
We have to Program to an interface and not for an implementation.
We have to favor object composition instead of inheritance.

Design Patterns Last Updated: November 2016 | Page 4 of 24


Usage of Design Patterns
Design Patterns have two main usages in software development.
We can speed up the Design patterns and can speed up the development process by
providing proven, tested development paradigms. Efficient software design may require
so much consideration of the issues which are not visible, until later in the
implementation.

Reusing design patterns may help in preventing subtle issues which can be causing
major problems and may improve code readability for architects and coders who are
familiar with patterns.

Normally, people can only understand how to apply some software design techniques
for some type of problems. These techniques are often very difficult when we are
applying them to some broad range of problems.

Design patterns can provide us some general solutions, which have been documented in
a format that doesnt require any specifics which are tied to particular problem.

Besides that, patterns can allow developers in communicating with well-known, and
names for software interactions. The design patterns which are common can be
improved over time, which makes them robust than the ad-hoc designs.

Best Practices
Design patterns have been evolving over a long time and they can provide us best
solutions for certain problems which have been faced during development of software. If
developers can learn these patterns, it can help them for learning software design in an
faster and easy way.

Design Patterns Last Updated: November 2016 | Page 5 of 24


Common platform for developers
Design patterns can provide us with standard terminology and can be specific to some
particular scenario. For example, a singleton design pattern can signify the use of single
object, so all the developers who are familiar with single design pattern can make use of
single object and can convey each other that program is following some singleton
pattern.

Types of Design Patterns


As per reference book Design Patterns - Elements of Reusable Object-Oriented Software
, in total we are having 23 design patterns which can be classified in three categories:
Structural, Creational and Behavioral patterns.

Creational Patterns
With these design patterns, we can get a way for creating objects while we are hiding
creation logic, and we are rather instantiating objects directly by the usage of new
operator. With this, we give program so much flexibility, in deciding which objects have
to be created for any given use case.

Structural Patterns
These design patterns are concerned with object and class composition. Concept of
inheritance have been used for composing interfaces and defining ways for composing
objects and obtain new functionalities.

Behavioral Patterns
With these design patterns, we are concerned with communication between the objects.

Design Patterns Last Updated: November 2016 | Page 6 of 24


Creational Design Patterns
In this document, we are going to see and know about Creational Design Patterns. We
will discuss about them in a theoretical and programmatic manner.

Design Pattern - Singleton Pattern

Singleton pattern can be said as one of the simplest design patterns in Java. This
singleton design pattern can be said as a design pattern, which comes under creational
pattern as this pattern is providing us with one of best ways for creating an object.

This pattern gives us with a single class, which is responsible for creating an object while
making sure, that only single object is getting created. This class gives us a way for
accessing its only object, and this can be accessed directly without any need for
instantiating the object of class.

Implementation Steps

Here, We're going to create some SingleObject class. SingleObject class can have a static
instance of itself and its constructor have been set as private.

With SingleObject class, we get a static method for getting its static instance to outside
world. Our demo class SingletonPatternDemo, will use the SingleObject class for getting
a SingleObject object.

Design Patterns Last Updated: November 2016 | Page 7 of 24


Step 1
We should Create a Singleton Class.

public class SingleObjectClass {

//we should create a object of SingleObject


private static SingleObjectClass instance = new SingleObjectClass();

// constructor is made private so that this class cannot be


//instantiated
private SingleObjectClass(){}

//Get the only object available


public static SingleObjectClass getInstance(){
return instance;
}

public void showMessage(){


System.out.println("Hello World!");
}
}

Design Patterns Last Updated: November 2016 | Page 8 of 24


Step 2
Get the only object from the singleton class.
SingletonPatternDemo.java

public class SingletonPatternDemo {

public static void main(String[] args) {

//this is a illegal construct

//We will get Compile Time Error: The constructor SingleObject() is


not visible

//SingleObjectClass object = new SingleObjectClass();

//Get the only object available


SingleObjectClass object = SingleObjectClass.getInstance();

//show the message


object.showMessage();
}
}

Step 3
The output.

Hello World!

Design Patterns Last Updated: November 2016 | Page 9 of 24


Design Patterns - Builder Pattern

With Builder pattern, we can build a complex object with the usage of simple objects
and we can follow a step by step approach for achieving this. This builder pattern comes
under creational pattern, as this pattern is providing with one of best ways for creating
an object.

A Builder class can build the final object on step by step basis. This builder is
independent of any other objects.

Implementation Steps

For this, We have to consider a business case of fast-food restaurant, where any typical
meal could be a cold drink and burger. Burger could be a Chicken Burger or Veg Burger
and it will be packed in some wrapper. Pepsi or coke could be a Cold drink and it will be
packed in a bottle.

Now, We will create an Item interface, which is going to represent food items such as
cold drinks and burgers, and concrete classes which implement the Item interface and a
Packing interface which represents the food items packaging and concrete classes
implementing the Packing interface as burger and they would be packed in wrapper and
cold drink which would be packed as bottle.

We then create a Meal class which has a ArrayList of Item and a MealBuilder which
builds different types of Meal objects which happens by combining Item.
BuilderPatternDemo, our demo class uses MealBuilder for building a Meal.

Design Patterns Last Updated: November 2016 | Page 10 of 24


Design Patterns Last Updated: November 2016 | Page 11 of 24
Step 1
Let us create an interface Item, and this is representing packing and food item.

Item.java
public interface Item {
public Packing packing();
public String name();
public float price();
}

Packing.java
public interface Packing {
public String pack();
}

Step 2
Now, Create concrete classes and they are implementing Packing interface.
Wrapper.java
public class Wrapper implements Packing {
@Override
public String pack() {
return "Wrapper";
}
}

Bottle.java
public class Bottle implements Packing {

@Override
public String pack() {
return "Bottle";
}
}
Step 3
After that, Create abstract classes that are implementing item interface, and they are
providing you with default functionalities.

Design Patterns Last Updated: November 2016 | Page 12 of 24


Burger.java
public abstract class Burger implements Item {

@Override
public abstract float price();

@Override
public Packing packing() {
return new Wrapper();
}
}

ColdDrink.java
public abstract class ColdDrink implements Item {
@Override
public abstract float price();
@Override
public Packing packing() {
return new Bottle();
}
}

Step 4
After them, Create concrete classes extending the ColdDrink and Burger classes
VegBurger.java

public class VegBurger extends Burger {


@Override
public String name() {
return "Veg Burger";
}
@Override
public float price() {
return 25.0f;
}
}

ChickenBurger.java

Design Patterns Last Updated: November 2016 | Page 13 of 24


public class ChickenBurger extends Burger {

@Override
public String name() {
return "Chicken Burger";
}

@Override
public float price() {
return 50.5f;
}
}

Coke.java
public class Coke extends ColdDrink {
@Override
public String name() {
return "Coke";
}
@Override
public float price() {
return 30.0f;
}
}
Pepsi.java
public class Pepsi extends ColdDrink {
@Override
public String name() {
return "Pepsi";
}
@Override
public float price() {
return 35.0f;
}
}

Step 5
Create a Meal class having Item objects defined above.
Meal.java

Design Patterns Last Updated: November 2016 | Page 14 of 24


import java.util.ArrayList;
import java.util.List;
public class Meal {

private List<Item> items = new ArrayList<Item>();

public float getCost(){


float cost = 0.0f;

for (Item item : items) {


cost += item.price();
}
return cost;
}

public void showItems(){

for (Item item : items) {


System.out.print("Item : " + item.name());
System.out.print(", Packing : " + item.packing().pack());
System.out.println(", Price : " + item.price());
}
}

public void addItem(Item item){


items.add(item);
}
}
Step 6
In step 6, Create a MealBuilder class, the actual builder class is now responsible for
creating the Meal objects.

MealBuilder.java

public class MealBuilder {

public Meal prepareNonVegMeal (){

Design Patterns Last Updated: November 2016 | Page 15 of 24


Meal meal = new Meal();
meal.addItem(new ChickenBurger());
meal.addItem(new Pepsi());
return meal;
}
public Meal prepareVegMeal (){
Meal meal = new Meal();
meal.addItem(new VegBurger());
meal.addItem(new Coke());
return meal;
}
}
Step 7
BuiderPatternDemo uses MealBuider to demonstrate builder pattern.
BuilderPatternDemo.java

public class BuilderPatternDemo {


public static void main(String[] args) {

MealBuilder mealBuilder = new MealBuilder();

Meal nonVegMeal = mealBuilder.prepareNonVegMeal();


System.out.println("\n\nNon-Veg Meal");
nonVegMeal.showItems();
System.out.println("Total Cost: " + nonVegMeal.getCost());

Meal vegMeal = mealBuilder.prepareVegMeal();


System.out.println("Veg Meal");
vegMeal.showItems();
System.out.println("Total Cost: " + vegMeal.getCost());

}
}

Design Patterns Last Updated: November 2016 | Page 16 of 24


Step 8
Verify the output.

Non-Veg Meal
Item : Chicken Burger, Packing : Wrapper, Price : 50.5
Item : Pepsi, Packing : Bottle, Price : 35.0
Total Cost: 85.5

Veg Meal
Item : Veg Burger, Packing : Wrapper, Price : 25.0
Item : Coke, Packing : Bottle, Price : 30.0
Total Cost: 55.0

Design Patterns Last Updated: November 2016 | Page 17 of 24


Design Patterns - Prototype Pattern

With Prototype pattern, we are going to create a duplicate object and also keep the
performance in mind. This Prototype Pattern normally comes under creational pattern,
and this pattern gives us with one of relevant ways for creating any object.

This pattern involves implementing a prototype interface which specifies to create a


clone of current object. This pattern can be used, when we want to create a object and
while creation of object may cost resources for us.

For example, suppose an object should to be created, that to, after some costly database
operation. For that to happen, we can cache the object, and we can return its clone on
any next update and can also request the database as and whenever it is needed thus
reducing the database calls.

Implementation Steps

We're going to create an abstract class Shape and concrete classes extending the Shape
class. A class ShapeCache is defined as a next step which stores shape objects in a
Hashtable and returns their clone when requested.

PrototypPatternDemo, our demo class will use ShapeCache class to get a Shape object.

Design Patterns Last Updated: November 2016 | Page 18 of 24


Step 1
Create an abstract class implementing Clonable interface.
Shape.java

public abstract class Shape implements Cloneable {

private String id;


protected String type;

abstract void draw();

public String getType(){


return type;
}

public String getId() {


return id;
}

Design Patterns Last Updated: November 2016 | Page 19 of 24


public void setId(String id) {
this.id = id;
}

public Object clone() {


Object clone = null;

try {
clone = super.clone();

} catch (CloneNotSupportedException e) {
e.printStackTrace();
}

return clone;
}
}

Step 2
Create concrete classes extending the above class.
Rectangle.java

public class Rectangle extends Shape {

public Rectangle(){
type = "Rectangle";
}

@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}

Design Patterns Last Updated: November 2016 | Page 20 of 24


Square.java

public class Square extends Shape {

public Square(){
type = "Square";
}

@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}

Circle.java

public class Circle extends Shape {

public Circle(){
type = "Circle";
}

@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}

Step 3
Create a class to get concrete classes from database and store them in a Hashtable.
ShapeCache.java

import java.util.Hashtable;

public class ShapeCache {

private static Hashtable<String, Shape> shapeMap = new Hashtable<String,


Shape>();

public static Shape getShape(String shapeId) {

Design Patterns Last Updated: November 2016 | Page 21 of 24


Shape cachedShape = shapeMap.get(shapeId);
return (Shape) cachedShape.clone();
}

// for each shape run database query and create shape


// shapeMap.put(shapeKey, shape);
// for example, we are adding three shapes

public static void loadCache() {


Circle circle = new Circle();
circle.setId("1");
shapeMap.put(circle.getId(),circle);

Square square = new Square();


square.setId("2");
shapeMap.put(square.getId(),square);

Rectangle rectangle = new Rectangle();


rectangle.setId("3");
shapeMap.put(rectangle.getId(), rectangle);
}
}

Step 4
PrototypePatternDemo uses ShapeCache class to get clones of shapes stored in a
Hashtable.
PrototypePatternDemo.java

public class PrototypePatternDemo {


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

Shape clonedShape = (Shape) ShapeCache.getShape("1");


System.out.println("Shape : " + clonedShape.getType());

Shape clonedShape2 = (Shape) ShapeCache.getShape("2");


System.out.println("Shape : " + clonedShape2.getType());

Shape clonedShape3 = (Shape) ShapeCache.getShape("3");


System.out.println("Shape : " + clonedShape3.getType());
}}

Design Patterns Last Updated: November 2016 | Page 22 of 24


Step 5
Verify the output.

Shape : Circle
Shape : Square
Shape : Rectangle

Design Patterns Last Updated: November 2016 | Page 23 of 24


Conclusion
Throughout this guide, we have come across and also covered various concepts which

are related to Design Patterns - Creational Patterns. Here, we also have covered about

the theoretical and programmatic part of creational patterns.

Design Patterns Last Updated: November 2016 | Page 24 of 24

Potrebbero piacerti anche