Java design patterns, first part. Creational design patterns (Factory method, Singleton and Builder pattern)


Design patterns were developed as solutions for common problems that every developer faces. Design patterns are classified based on their main purpose; a design pattern may be any of the following types:

  •  Creational patterns
  •  Structural patterns
  •  Behavioral patterns

In this post, we are primarily focused on creational patterns and their implementation in Java.

Factory method

Factory method is a design pattern that centralizes the creation of objects that follow a hierarchical structure; this pattern is composed by the following elements:

  •  A factory class: In this case, as an example, we create the class SpritesFactory.
  • The product to be built: For this example, the Java objects built by the application.

Our example will be build using following hierarchical structure:
factory

Modelling our application

/*
*/
package com.raidentrance.model.stripes;

import java.awt.Graphics;

/**
 * @author raidentrance
 *
 */
public abstract class Sprite {
	protected int x;
	protected int y;
	protected int width;
	protected int heigth;

	public abstract void draw(Graphics g);

	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public int getHeigth() {
		return heigth;
	}

	public void setHeigth(int heigth) {
		this.heigth = heigth;
	}
}

The Sprites class is an abstract class where we define common methods for all of the Sprites, such as: getX(), setX(int x), getY(), setY(int y), getWidth(),setWidth(int width), getHeigth() and  setHeigth(); as well as an abstract method called draw(Graphics g) that is different for each one of the implementations.

package com.raidentrance.model.stripes;

import java.awt.Graphics;

/**
 * @author raidentrance
 *
 */

public class Hero extends Sprite {

	@Override
	public void draw(Graphics g) {
		System.out.println("Drawing a hero");
	}
}
/*
**
*/
package com.raidentrance.model.stripes;

import java.awt.Graphics;

/**
 * @author raidentrance
 **/
public class BadBoy extends Sprite {
	@Override
	public void draw(Graphics g) {
		System.out.println("Drawing a bad boy");
	}
}

Hero.java and BadBoy.java are Sprite.java subclasses. We use the Factory method to instantiate these subclasses.

Creating the object factory class

The next step is to create the class responsible of following the Factory method design pattern. This class creates the instances within the application.

/**
*
*/
package com.raidentrance.factory;

import com.google.common.base.Preconditions;
import com.raidentrance.model.stripes.BadBoy;
import com.raidentrance.model.stripes.Hero;
import com.raidentrance.model.stripes.Sprite;

/**
 * @author raidentrance
 *
 */

public class SpritesFactory {
	public static enum SpriteType {
		HERO, BAD_BOY
	}

	public static Sprite createStripe(SpriteType type) {
		Preconditions.checkNotNull(type);
		switch (type) {
		case HERO:
			return new Hero();
		case BAD_BOY:
			return new BadBoy();
		}
		throw new IllegalArgumentException();
	}
}

There are two key points to highlight in the SpriteFactory class. Firstly, it contains an enumeration that defines all of the possible types of objects than can be built. Secondly, the method createStripes(StripeType type) receives an SpriteType as argument and depending on this argument it returns the corresponding instance.

Putting all together

Finally, we create a class to gather the classes previously described and observe how the objects are instantiated.

/**
*
*/
package com.raidentrance.factory;

import com.raidentrance.model.stripes.Sprite;

/**
 * @author raidentrance
 *
 */

public class Sample {
	/**
	 * @param args
	 */
	public static void main(String[] args) {

		Sprite sprite = SpritesFactory.createStripe(SpritesFactory.SpriteType.HERO);
		sprite.draw(null);
		Sprite sprite2 = SpritesFactory.createStripe(SpritesFactory.SpriteType.BAD_BOY);
		sprite2.draw(null);
	}
}

Output

Drawing a hero
Drawing a bad boy
Singleton pattern

Singleton pattern is used to define a class that contains a single instance and provides a single point of access to it.

In the following example, we create a Singleton class to define the set up parameters of an application.

Defining a class for error handling

/**
*
*/
package com.raidentrance.commons;

/**
 * @author raidentrance
 *
 */

public enum ErrorResult {

	EMPTRY_RESULT("%s cannot be null"), INVALID_ARGUMENT("%s is not a valid type");
	private String message;

	private ErrorResult(String message) {
		this.message = message;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
}
/**
*
*/

package com.raidentrance.model;

/**
 * @author raidentrance
 *
 */

public class BussinessException extends Exception {

	private static final long serialVersionUID = 1788240335231977221L;

	public BussinessException(String msg) {
		super(msg);
	}
}

Defining the Singleton class

/**
*
*/

package com.raidentrance.singleton;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import com.google.common.base.Preconditions;
import com.raidentrance.commons.ErrorResult;
import com.raidentrance.model.BussinessException;

/**
 * @author raidentrance
 *
 */

public class Settings {
	private String host;
	private int port;
	private String context;
	private String username;
	private String password;
	private static Settings instance = new Settings();

	private Settings() {
	}

	public static Settings getInstance() {
		return instance;
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getContext() {
		return context;
	}

	public void setContext(String context) {
		this.context = context;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getUrl() {
		Preconditions.checkNotNull(host,
				new BussinessException(String.format(ErrorResult.EMPTRY_RESULT.getMessage(), "host")));
		return host + ":" + port + context;
	}

	public String getCredentials() {
		return "Basic ".concat(Base64.getEncoder()
				.encodeToString(username.concat(":").concat(password).getBytes(StandardCharsets.UTF_8)));
	}
}

Points to highlight:

  1. Private constructor: It is fundamental to create a private constructor, by this means, the Singleton class is the only one capable to instantiate itself.
  2. Private static instance: It is necessary to define the instance as private and static, in order to make this variable accessible only inside the Singleton class.
  3. getInstance() method: This is the only point of access to the instance.

Putting all together.

/**
 *
 */
package com.raidentrance.singleton;

/**
 * @author raidentrance
 *
 */
public class Sample {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Settings settings = Settings.getInstance();
		System.out.println("Setting default settings.");
		settings.setHost("http://localhost");
		settings.setPort(8080);
		settings.setContext("/rest");
		settings.setUsername("user");
		settings.setPassword("SecretPassword");

		System.out.println(Settings.getInstance().getUrl());
		System.out.println(Settings.getInstance().getCredentials());

		System.out.println("Updating settings.");
		settings = Settings.getInstance();
		settings.setHost("http://192.168.5.1");
		settings.setUsername("prodUser");
		settings.setPassword("UltraSecretPassword");

		System.out.println(Settings.getInstance().getUrl());
		System.out.println(Settings.getInstance().getCredentials());
	}
}

Output

Setting default settings.
http://localhost:8080/rest
Basic dXNlcjpTZWNyZXRQYXNzd29yZA==
Updating settings.
http://72.51.22.13:8080/rest
Basic cHJvZFVzZXI6VWx0cmFTZWNyZXRQYXNzd29yZA==

As shown in this example, it doesn’t really matter how many times you invoke the getInstance() method, this will always return the same instance.

Builder Pattern

This design pattern is used to build complex object step by step.

Modelling our application

/**
 *
 */
package com.raidentrance.model;

import java.util.Date;

/**
 * @author raidentrance
 *
 */
public class Person {
	private String name;
	private Date birthDate;
	private int age;

	public Person() {
	}

	public Person(String name, Date birthDate, int age) {
		super();
		this.name = name;
		this.birthDate = birthDate;
		this.age = age;
	}

	public String getName() {
		return name;
	}

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

	public Date getBirthDate() {
		return birthDate;
	}

	public void setBirthDate(Date birthDate) {
		this.birthDate = birthDate;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", birthDate=" + birthDate + ", age=" + age + "]";
	}
}

 

/**
 *
 */
package com.raidentrance.model;

/**
 * @author raidentrance
 *
 */
public class Book {
    private String isbn;
    private String title;
    private String author;
    private double price;

    public Book() {
    }

    public Book(String isbn, String title, String author, double price) {
        super();
        this.isbn = isbn;
        this.title = title;
        this.author = author;
        this.price = price;
    }

    public String getIsbn() {
        return isbn;
    }

    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book [isbn=" + isbn + ", title=" + title + ", author=" + author + ", price=" + price + "]";
    }

}

Helper class to calculate the age

The following class calculates a person’s age based on her birthday.

/**
 *
 */
package com.raidentrance.commons;

import java.util.Calendar;
import java.util.Date;

/**
 * @author raidentrance
 *
 */
public class TimeHelper {
    public static int getAge(Date birthDate) {
        Calendar dob = Calendar.getInstance();
        dob.setTime(birthDate);
        Calendar today = Calendar.getInstance();
        int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
        if (today.get(Calendar.MONTH) < dob.get(Calendar.MONTH)) {
            age--;
        } else if (today.get(Calendar.MONTH) == dob.get(Calendar.MONTH)
                && today.get(Calendar.DAY_OF_MONTH) < dob.get(Calendar.DAY_OF_MONTH)) {
            age--;
        }
        return age;
    }
}

Creating an abstract builder

An abstract builder class allows you to follow the same structure in all of the builders that you might want to develop. In this example, we create two builders, the first one to create Person objects and the second one to create Book objects, both of them extend AbstractBuilder.

/**
 *
 */
package com.raidentrance.builder.commons;

/**
 * @author raidentrance
 *
 */
public abstract class AbstractBuilder<T> {
    protected T instance;

    public AbstractBuilder(T instance) {
        this.instance = instance;
    }

    public T build() {
        inject();
        validate();
        return instance;
    }

    public abstract void validate();

    public abstract void inject();
}

Points to highlight on the AbstractBuilder class:

  1. This class has a generic instance that will contain the object that we want to build.
  2. Its constructor receives this instance as argument.
  3. It contains three important methods:
    • inject(): This method is used to generate values based on the attributes that it has.
    • validate(): This method validates that all of the prerequisites to correctly build an object are accomplished.
    • build(): This method calls the inject() and validate() method, and returns the instance.

Creating builders

PersonBuilder.java

/**
 *
 */
package com.raidentrance.builder;

import java.util.Date;

import com.google.common.base.Preconditions;
import com.raidentrance.builder.commons.AbstractBuilder;
import com.raidentrance.commons.ErrorResult;
import com.raidentrance.commons.TimeHelper;
import com.raidentrance.model.BussinessException;
import com.raidentrance.model.Person;

/**
 * @author raidentrance
 *
 */
public class PersonBuilder extends AbstractBuilder<Person> {

    public PersonBuilder() {
        super(new Person());
    }

    public PersonBuilder setName(String name) {
        instance.setName(name);
        return this;
    }

    public PersonBuilder setBirthDate(Date birthDate) {
        instance.setBirthDate(birthDate);
        return this;
    }

    @Override
    public void validate() {
        Preconditions.checkNotNull(instance.getName(),
                new BussinessException(String.format(ErrorResult.EMPTRY_RESULT.getMessage(), "Name")));
        Preconditions.checkNotNull(instance.getBirthDate(),
                new BussinessException(String.format(ErrorResult.EMPTRY_RESULT.getMessage(), "Birth date")));
        Preconditions.checkNotNull(instance.getAge(),
                new BussinessException(String.format(ErrorResult.EMPTRY_RESULT.getMessage(), "Age")));
    }

    @Override
    public void inject() {
        Preconditions.checkNotNull(instance.getBirthDate(),
                new BussinessException(String.format(ErrorResult.EMPTRY_RESULT.getMessage(), "Birth date")));
        instance.setAge(TimeHelper.getAge(instance.getBirthDate()));
    }
}

Points to highlight on the PersonBuilder class:

  1. The PersonBuilder constructor sends a new Person instance as argument.
  2. Each setter method returns a PersonBuilder instance.
  3. The inject() method is used to generate the age based on a birthday.
  4. The validate() method validates that the variables are not null.
  5. The build() method is already defined on the AbstractBuilder class and it returns a complete and correctly formed instance.

BookBuilder.java

package com.raidentrance.builder;

import com.google.common.base.Preconditions;
import com.raidentrance.builder.commons.AbstractBuilder;
import com.raidentrance.commons.ErrorResult;
import com.raidentrance.model.Book;
import com.raidentrance.model.BussinessException;

/**
 * @author raidentrance
 *
 */
public class BookBuilder extends AbstractBuilder<Book> {

    public BookBuilder() {
        super(new Book());
    }

    public BookBuilder setIsbn(String isbn) {
        instance.setIsbn(isbn);
        return this;
    }

    public BookBuilder setTitle(String title) {
        instance.setTitle(title);
        return this;
    }

    public BookBuilder setAuthor(String author) {
        instance.setAuthor(author);
        return this;
    }

    public BookBuilder setPrice(double price) {
        instance.setPrice(price);
        return this;
    }

    @Override
    public void validate() {
        Preconditions.checkNotNull(instance.getIsbn(),
                new BussinessException(String.format(ErrorResult.EMPTRY_RESULT.getMessage(), "Isbn")));
    }

    @Override
    public void inject() {

    }
}

You can find the code previously explained in the following link:  https://github.com/raidentrance/design-patterns

Author: Alejandro Agapito Bautista

Twitter: @raidentrance

e-mail:raidentrance@gmail.com

Translated By: Oscar Camacho – melchior01

Contact: adamfirstangel@hotmail.com

Anuncios

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión /  Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión /  Cambiar )

Conectando a %s