Created
August 23, 2011 15:41
-
-
Save hamstar/1165493 to your computer and use it in GitHub Desktop.
example of drying up code through inheritance, the facade pattern, and convention over configuration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Get a model from the database, client says | |
Connection conn = DatabaseConnectionHelper.getConnection(); // make this static | |
DBFacade db = new DBFacade( conn ); | |
ExampleModel exModel = ExampleModel.find( db, 15 ); | |
exModel.setName('blah').save(); | |
exModel.delete(); | |
// classes | |
public class SuperModel { | |
protected DBFacade db; | |
protected Map row; | |
public SuperModel( DBFacade db, int id ) { | |
this.db = db; | |
} | |
/** | |
* Get the name of the table by figuring out the name of this model | |
* and using that as the table name (minus Model) | |
* ( you could also store a constant in the child table called TABLE_NAME ) | |
*/ | |
final public String getTable() { | |
String[] strings = this.getClass().getName().split("\\."); // split the package/class | |
String className = strings[1]; | |
// Build the table name | |
return className.substring(0, className.length()-5).toLowerCase(); | |
} | |
private void populateModel( int id ) { | |
Map where = new Map<String, String>(); | |
where.put( 'id', id.toString() ); | |
row = this.db.where( where ).get( this.getTable() ); | |
} | |
public void delete() { | |
Map where = new Map; | |
where.put( 'id', this.row.get('id') ); | |
this.db.where( where ).delete( this.getTable() ); | |
} | |
public void save() { | |
// need to detect if this is an insert or an update | |
} | |
/** | |
* Act as a mini factory in static context | |
*/ | |
} | |
public class ExampleModel extends SuperModel { | |
public ExampleModel( DBFacade db, int id ) { | |
super( db, id ); | |
} | |
public static ExampleModel find( DBFacade db, int id ) { | |
return new ExampleModel( db, id ); | |
} | |
public String getName() { | |
return this.row.get('name'); | |
} | |
} | |
public class DBFacade { | |
private Connection conn; | |
public int lastInsertId() { | |
} | |
public ArrayList getColumnList() { | |
} | |
public DBFacade where() { | |
return this; | |
} | |
public DBFacade select() { | |
return this; | |
} | |
public Map get( String table ) throws SQLException { | |
} | |
public DBFacade insert( Map data, String table ) throws SQLException { | |
return this; | |
} | |
public DBFacade update( Map data, String table ) throws SQLException { | |
return this; | |
} | |
public DBFacade delete( String table ) throws SQLException { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment