Factory Pattern Android
As we all know we have design pattern in programming languages. So Factory Pattern in one of them and it is widely used. I have used it in my app
It falls under Creational Design Pattern.
So lets start with Word Factory, factory is a place where something is created. So here Object is created, without having knowledge to client about logic.
We will go Step by Step.
In Factory Pattern we have 1 interface and some classes need to implement that interface .
interface MusicPlayer{
void Play()
}
Now i have 2 classes one is Audio Player and Other is Video Player .
class AudioPlayer implements MusicPlayer{
@Override void Play()
}class VideoPlayer implements MusicPlayer{
@Override void Play()
}
Now Create a MusicPlayer Factory.
class MusicPlayerFactory {public MusicPlayer musicPlayer(String type) {if(type == null) {
return null;
}if(type == "audio") {
return new AudioPlayer();
}if(type == "video") {
return new VideoPlayer();
}
}
}
Now Access Audio and Video as below information.
class MusicService {
void getMusic() {MusicFactory musicFactory = new MusciFactory();
Music music = musicFactory.musicPlayer("audio");
music.play();}
}
So this is Factory Pattern, and you can how easy it is and its practical implementation in android app.
I have used this pattern in app : https://play.google.com/store/apps/details?id=com.mcmedia.kidslearningapp