Factory Pattern Example

Factory pattern is one of most used design pattern in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.

In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.

 

Step 1

Create a base class (interface or abstract class)  MediaFormatPlayer.java

public abstract class MediaFormatPlayer {
protected abstract void playMedia();
}

Step 2

Create concrete classes implementing the same interface.  MovieMediaFormatPlayer .java and MusicMediaFormatPlayer.java

public class MovieMediaFormatPlayer extends MediaFormatPlayer {
@Override
public void playMedia() {
System.out.println("Play Movie Media");
}
}



public class MusicMediaFormatPlayer extends MediaFormatPlayer {

@Override
public void playMedia() {
System.out.println("Play Music Media");
}

}


public enum MediaCellType {
	 MUSIC(1,"MUSIC_ID"),
	 MOVIE(2, "MOVIE_ID"),
	 DOCUMENT(3,"DOCUMENT_ID");
	 private int id;
	 private String key;	
	 static{
	 }
	 private MediaCellType(int id, String key) {
	        this.id = id;
	        this.key=key;
	    }
	 
	 
}


Step 3

Create a Factory to generate object of concrete class based on given information.


public class MediaTypeFactory {
	private static HashMap < MediaCellType  ,  Class <?> []>  mediaTypeMap = new HashMap<MediaCellType, Class <?>[]>();
	public static final int MEDIA_FORMAT_PLAYER = 0;
	static {
		mediaTypeMap.put(MediaCellType.MUSIC, new Class[]{MusicMediaFormatPlayer.class});
		mediaTypeMap.put(MediaCellType.MOVIE, new Class[]{MovieMediaFormatPlayer.class});
		
	}
	public static MediaFormatPlayer getMediaFormatPlayer(MediaCellType mediaCellType){
		MediaFormatPlayer mediaFormatPlayerAdapter = null;
		try {
			Class<?>[] classes = mediaTypeMap.get(mediaCellType);
			if(classes == null) return null;
			Class<?> clazz = classes[MEDIA_FORMAT_PLAYER];
			mediaFormatPlayerAdapter  =(MediaFormatPlayer)clazz.newInstance();
		
		} catch(Exception e ){
			throw new RuntimeException(e);
		}
		return mediaFormatPlayerAdapter; 
		
	}
}

Step 4

Write a test!

public class MediaFactoryTest {
	private MediaTypeFactory mediaTypeFactory ;
	
	@Before
	public void setUp() throws Exception {
		mediaTypeFactory = new MediaTypeFactory();
	}
	
	@Test
	public void testPlayMoviePlayer()  {
		  //1. Get an object of MovieMediaFormat Player and call its play method.
	      MovieMediaFormatPlayer moviePlayer = (MovieMediaFormatPlayer) MediaTypeFactory.getMediaFormatPlayer(MediaCellType.MOVIE);
	      //call play media method
	      moviePlayer.playMedia();
	      assertNotNull(moviePlayer);
	}
	
	@Test
	public void testPlayMusicPlayer()  {
		//2. Get an object of MusicMediaFormat Player and call its play method.
	    MusicMediaFormatPlayer musicPlayer = (MusicMediaFormatPlayer) MediaTypeFactory.getMediaFormatPlayer(MediaCellType.MUSIC);
	      //call play media method
	    musicPlayer.playMedia();
	    assertNotNull(musicPlayer);
	}
	
	
	
	 
	
}

Published by anthonykuong

Anthony is a versatile Software professional with around 10 years of experience. He is a Full Stack developer experienced with clients in the Financial, Health and Supply Chain industries. He is experienced with MVC frameworks ( Spring Boot) , SPA frameworks ( Angular , VueJS), and also supports automated build deployments and packaging for development, qa, and production servers.. He has delivered rich user experience using Modern web technologies and techniques such are HTML5, CSS3, ECMAScript 6 (ES6)/ ECMAScript 2015, CSS pre-processors (SASS, Less), JavaScript build tools (Grunt, Gulp) , various UI Frameworks including AngularJS , Knockout JS , and CSS Frameworks including Bootstrap, and Foundation. He is adaptable to new technologies and frameworks. He is a rigorous, quality-conscious contributor with solid analytical skills. I can also be found on youtube - Youtube Channel: https://www.youtube.com/user/akuong/

Leave a comment