Java Factory pattern

When do we use it?

Design patterns are used when you have a super class with multiple sub classes depending on output you need to return one of the sub classes.

Usage Method 1: Apply a Singleton pattern

Usage Method 2: make the factory method static

advantage

  • Provide approach to code for interface rather than implementation
  • Changes of a super class is easier and easy to extend
  • Abstraction  between implementation and client class through inheritance

Usages in JDK:Calendar, valueOf() method

Now we are going to create a Room interface concluding with classes and implementing a Room interface with a RoomFactory and Main class.

Step 1 :Create Room interface

public interface Room {
void book();

}

Step 2 :Create DoubleRoom class implementing same interface

public class DoubleRoom implements Room {
private float price;

	@Override
	public void book() {
		System.out.println("book double room \n");
		
	}

	public float getPrice() {
		return price;
	}

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

}

Step 3 :Create VIPRoom class

public class VIPRoom implements Room {
private int flatscreenSize;

	@Override
	public void book() {
		System.out.println("book VIP room \n");
		
	}

	public int getFlatscreenSize() {
		return flatscreenSize;
	}

	public void setFlatscreenSize(int flatscreenSize) {
		this.flatscreenSize = flatscreenSize;
	}

}

Step 4 :Create FamilyRoom class

public class FamilyRoom implements Room {
private int countChildren;

public int getCountChildren() {
	return countChildren;
}

public void setCountChildren(int countChildren) {
	this.countChildren = countChildren;
}

@Override
public void book() {
	System.out.println("book family room \n");
	
}

}

Step 5 :Create RoomFactory class generating object of information to get type of Room

public class RoomFactory {
	 public static Room getRoom(String roomtype) {
		 if(roomtype == null){
	         return null;
	      }		
	      if(roomtype.equalsIgnoreCase("DoubleRoom")){
	         return new DoubleRoom();
	         
	      } else if(roomtype.equalsIgnoreCase("VIPRoom")){
	         return new VIPRoom();
	         
	      } else if(roomtype.equalsIgnoreCase("FamilyRoom")){
	         return new FamilyRoom();
	     }
 
return null;
		 
		 
	 }
}

Step 6 :Create Main class 

public class Main {
public static void main(String[] args) {
	RoomFactory rf = new RoomFactory();
	
	Room room1 = RoomFactory.getRoom("DoubleRoom");
	room1.book();
	
	Room room2 = RoomFactory.getRoom("VIPRoom");
	room2.book();
	
	
	Room room3 = RoomFactory.getRoom("FamilyRoom");
	room3.book();
}
}

:Output

book double room 

book VIP room 

book family room 

Leave a Reply

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