Java Design Pattern – Factory Pattern

Factory Pattern is a kind of Creation Pattern. Factory Pattern provides an interface for integration and hidden the complex implementation of related components.

The tutorial will help you create a factory pattern based on concept above.

I. Technology use for Factory Pattern

– Java 8
– Eclipse: Version: Mars.2 Release (4.5.2)

II. Overview Tutorial

java factory design pattern uml

Create a Car Factory Pattern as Java classes:
– Car interface
– Implements Car interface: Audi class, BMW class, Mercedes class.
– Implements Car Factory: CarFactory class.
– CarType class: defines all kind of car that Car Factory products.

java factory design pattern

III. Practices
1. Create a Car Interface
public interface Car {
	String info();
}
2. Implement Car Interface

– Create Audi class:

public class Audi implements Car {

	int id;

	public Audi() {
		Random randomno = new Random();
		id = randomno.nextInt();
	}

	@Override
	public String info() {
		String msg = String.format("Hello World! I'm a new %s. My Id = %d", "Audi", id);
		return msg;
	}
}

– Create BMW class:

public class BMW implements Car{

	int id;
	
	public BMW() {
		Random randomno = new Random();
		id = randomno.nextInt();
	}
	
	@Override
	public String info() {
		String msg = String.format("Hello World! I'm a new %s. My Id = %d"
									, "BMW", id);
		return msg;
	}
}

– Create Mercedes class:

public class Mercedes implements Car{
	
	int id;
	
	public Mercedes() {
		Random randomno = new Random();
		id = randomno.nextInt();
	}
	
	@Override
	public String info() {
		String msg = String.format("Hello World! I'm a new %s. My Id = %d"
									, "Mercedes", id);
		return msg;
	}
}
3. Define Car Type

– Create CarType enum:

public enum CarType {
	Mercedes, Audi, BMW
}
4. Create Car Factory

– Create CarFactory class:

public class CarFactory {
	public Car produce(CarType type){
		Car car = null;
		switch(type){
			case Mercedes: 
				car = new Mercedes();
				break;
			case Audi:
				car = new Audi();
				break;
			case BMW:
				car = new BMW();
				break;
			default:
				break;
		}
		return car;
	}
}
5. Create Main Class
public class MainClass {
	public static void main(String[] args) {
		List cars = new ArrayList();
		CarFactory carFactory = new CarFactory();
		cars.add(carFactory.produce(CarType.Mercedes));
		cars.add(carFactory.produce(CarType.Audi));
		cars.add(carFactory.produce(CarType.BMW));
		
		for(Car c: cars){
			System.out.println(c.info());
		}
	}
}
IV. Run

Result

Hello World! I'm a new Mercedes. My Id = 528695596
Hello World! I'm a new Audi. My Id = 1347512690
Hello World! I'm a new BMW. My Id = -2050050610
V. Sourcecode

java factory design pattern



By grokonez | October 14, 2016.

Last updated on June 4, 2017.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*