Skip to content

Instantly share code, notes, and snippets.

@Hesamedin
Last active March 23, 2016 00:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hesamedin/4f32dac6be2fa575a87c to your computer and use it in GitHub Desktop.
Save Hesamedin/4f32dac6be2fa575a87c to your computer and use it in GitHub Desktop.
Factory Design pattern for Storing Object in DB
public class Comment {
long commentId;
String message;
// Other setter/getter methodes
...
}
public class Database_A implements IDatabase {
@Override
public void insert(Comment comment) {
System.out.println("Inside Database_A::insert() method.");
}
@Override
public Comment read(long commentId) {
System.out.println("Inside Database_A::read() method.");
}
@Override
public void update(long commentId) {
System.out.println("Inside Database_A::update() method.");
}
@Override
public void delete(long commentId) {
System.out.println("Inside Database_A::delete() method.");
}
}
public class Database_B implements IDatabase {
@Override
public void insert(Comment comment) {
System.out.println("Inside Database_B::insert() method.");
}
@Override
public Comment read(long commentId) {
System.out.println("Inside Database_B::read() method.");
}
@Override
public void update(long commentId) {
System.out.println("Inside Database_B::update() method.");
}
@Override
public void delete(long commentId) {
System.out.println("Inside Database_B::delete() method.");
}
}
public class DatabaseFactory {
//use getDatabase method to get object of type IDatabase
public IDatabase getDatabase(String dbType){
if(TextUtils.empty(dbType)){
return null;
}
if(dbType.equalsIgnoreCase("Database_A")){
return new Database_A();
}
else if(dbType.equalsIgnoreCase("Database_B")){
return new Database_B();
}
return null;
}
}
public class FactoryPatternDemo {
public static void main(String[] args) {
Comment comment = new Comment();
comment.setMessage("Hello P&R :)");
DatabaseFactory dbFactory = new DatabaseFactory();
// get an object of Database_A and call its insert method. Other methods can be called similarly.
IDatabase db_A = dbFactory.getDatabase("Database_A");
db_A.insert(comment);
// get an object of Database_B and call its insert method. Other methods can be called similarly.
IDatabase db_B = dbFactory.getDatabase("Database_B");
db_B.insert(comment);
}
}
public interface IDatabase {
void insert(Comment comment);
Comment read(long commentId);
void update(Comment comment);
void delete(long commentId);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment