1 / 65

Object Oriented Methods

Object Oriented Methods. Architectural Patterns 3. Content. Patterns for Enterprise Application Architecture [Fowler] - continued Data Source Patterns Concurrency Patterns. References. Martin Fowler et. al, Patterns of Enterprise Application Architecture, Addison Wesley, 2003 [Fowler].

carrierm
Download Presentation

Object Oriented Methods

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Object Oriented Methods Architectural Patterns 3 Computer Science Department, TUC-N

  2. Content • Patterns for Enterprise Application Architecture [Fowler] - continued • Data Source Patterns • Concurrency Patterns Computer Science Department, TUC-N

  3. References • Martin Fowler et. al, Patterns of Enterprise Application Architecture, Addison Wesley, 2003 [Fowler] Computer Science Department, TUC-N

  4. Data Source Patterns • Pure Data Source Patterns • Gateways • Row Data Gateway (RDG) • Table Data Gateway (TDG) • Data Mapper • Hybrid Data Source Pattern (discussed) • Active Record • Table Module Computer Science Department, TUC-N

  5. Data Source Patterns • Hide SQL. • Provide an abstraction for • One data row. • A collection of data row(s). • OR mapping problems • Links • Inheritance Computer Science Department, TUC-N

  6. Table Data Gateway Fowler: An object that acts as a gateway to a database table. One instance handles all the rows in the table. A TDG hides all the SQL for accessing a single DB table or DB view: selects, updates, deletes. Computer Science Department, TUC-N

  7. TDG Computer Science Department, TUC-N

  8. Features • Find, insert, update, delete methods • Challenge: how it returns information from a query ? • Data Transfer Object • Record Set • Goes well with Table Module • Suitable for Transaction Scripts Computer Science Department, TUC-N

  9. Using ADO.NET DataSets Computer Science Department, TUC-N

  10. Implementation class DataSetHolder... public DataSet Data = new DataSet(); private Hashtable DataAdapters = new Hashtable(); class DataGateway... public DataSetHolder Holder; public DataSet Data { get {return Holder.Data;} } Computer Science Department, TUC-N

  11. Implementing find behavior class DataGateway... public void LoadAll() { String commandString = String.Format("select * from {0}", TableName); Holder.FillData(commandString, TableName); } public void LoadWhere(String whereClause) { String commandString = String.Format("select * from {0} where {1}", TableName,whereClause); Holder.FillData(commandString, TableName); } abstract public String TableName {get;} Computer Science Department, TUC-N

  12. Implementation continued class PersonGateway... public override String TableName { get {return "Person";} } class DataSetHolder... public void FillData(String query, String tableName) { if (DataAdapters.Contains(tableName)) throw new MutlipleLoadException(); OleDbDataAdapter da = new OleDbDataAdapter(query, DB.Connection); OleDbCommandBuilder builder = new OleDbCommandBuilder(da); da.Fill(Data, tableName); DataAdapters.Add(tableName, da); } Computer Science Department, TUC-N

  13. Row Data Gateway • An object that acts as a single record in the data source • There is one instance per row • Fowler RDG combines two roles Class …Finder with find(id):Gateway method which returns the ‘object’ Class …Gateway which is the ‘object’ Computer Science Department, TUC-N

  14. Row Data Gateway Computer Science Department, TUC-N

  15. How it works? • Separate data access code from Domain logic • type conversion from the data source types to the in-memory types • works particularly well for Transaction Scripts • where to put the find operations that generate the Row Data ? Computer Science Department, TUC-N

  16. How it works? • static find methods -> hinders polymorphism • separate finder objects • each table in a relational database will have: • one finder class • one gateway class for the results. Computer Science Department, TUC-N

  17. RDG behavior Computer Science Department, TUC-N

  18. Implementation class PersonGateway... private String lastName; private String firstName; private int numberOfDependents; public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } … private static final String updateStatementString = "UPDATE people " + " set lastname = ?, firstname = ?, number_of_dependents = ? " + " where id = ?"; public void update() { …} … Computer Science Department, TUC-N

  19. PersonFinder class PersonFinder... private final static String findStatementString = "SELECT id, lastname, firstname, number_of_dependents " + " from people " + " WHERE id = ?"; public PersonGateway find(Long id) { PersonGateway result = (PersonGateway)Registry.getPerson(id); if (result != null) return result; try { findStatement = DB.prepare(findStatementString); findStatement.setLong(1, id.longValue()); rs = findStatement.executeQuery(); rs.next(); result = PersonGateway.load(rs); return result; } catch (SQLException e) { throw new ApplicationException(e); } Computer Science Department, TUC-N

  20. Using RDG in Transaction Scripts PersonFinder finder = new PersonFinder(); Iterator people = finder.findResponsibles().iterator(); StringBuffer result = new StringBuffer(); while (people.hasNext()) { PersonGateway each = (PersonGateway) people.next(); result.append(each.getLastName()); result.append("\t"); result.append(each.getFirstName()); result.append("\t"); result.append(String.valueOf(each.getNumberOfDependents())); result.append("\n"); } return result.toString(); Computer Science Department, TUC-N

  21. Using RDG as a holder for the domain object class Person... private PersonGateway data; public Person(PersonGateway data) { this.data = data; } public int getNumberOfDependents() { return data.getNumberOfDependents(); } Computer Science Department, TUC-N

  22. Data Mappers • Acts as an intermediary between Domain Models and the database. • Allows Domain Models and Data Source classes to be independent of each other Computer Science Department, TUC-N

  23. Data Mapper Layer … • Can either • Access the database itself, or • Make use of a Table Data Gateway. • Does not contain Domain Logic. • When it uses a TDG, the Data Mapper can be placed in the (lower) Domain layer. Computer Science Department, TUC-N

  24. How it works – retrieving data Computer Science Department, TUC-N

  25. Finding objects Computer Science Department, TUC-N

  26. How it works – updating data Computer Science Department, TUC-N

  27. Features • Independent database schema and object model • Extra layer • Works well with Domain Model Computer Science Department, TUC-N

  28. Implementation class Person... private String lastName; private String firstName; private int numberOfDependents; create table people (ID int primary key, lastname varchar, firstname varchar, number_of_dependents int) Computer Science Department, TUC-N

  29. Mapper class implements finder class PersonMapper... protected String findStatement() { return "SELECT " + COLUMNS + " FROM people" + " WHERE id = ?"; } public static final String COLUMNS = " id, lastname, firstname, number_of_dependents "; public Person find(Long id) { return (Person) abstractFind(id); } Computer Science Department, TUC-N

  30. AbstractMapper class AbstractMapper... protected Map loadedMap = new HashMap(); abstract protected String findStatement(); protected DomainObject abstractFind(Long id) { DomainObject result = (DomainObject) loadedMap.get(id); if (result != null) return result; PreparedStatement findStatement = null; try { findStatement = DB.prepare(findStatement()); findStatement.setLong(1, id.longValue()); ResultSet rs = findStatement.executeQuery(); rs.next(); result = load(rs); return result; } catch (SQLException e) { throw new ApplicationException(e); } finally { DB.cleanUp(findStatement); } } Computer Science Department, TUC-N

  31. Load method in AbstractMapper class AbstractMapper... protected DomainObject load(ResultSet rs) throws SQLException { Long id = new Long(rs.getLong(1)); if (loadedMap.containsKey(id)) return (DomainObject) loadedMap.get(id); DomainObject result = doLoad(id, rs); loadedMap.put(id, result); return result; } abstract protected DomainObject doLoad(Long id, ResultSet rs) throws SQLException; Computer Science Department, TUC-N

  32. doLoad in PersonMapper class PersonMapper... protected DomainObject doLoad(Long id, ResultSet rs) throws SQLException { String lastNameArg = rs.getString(2); String firstNameArg = rs.getString(3); int numDependentsArg = rs.getInt(4); return new Person(id, lastNameArg, firstNameArg, numDependentsArg); } Computer Science Department, TUC-N

  33. Separating finders Computer Science Department, TUC-N

  34. Hybrid Data Source Patterns • Active Record = RDG + Domain Logic. • Table Module ≈ TDG + Domain Logic. • TDG like module that processes ResultSets. Computer Science Department, TUC-N

  35. Identity Map Ensure each object only gets loaded once by keeping every loaded object in a map. Lookup objects using the map when referring to them Computer Science Department, TUC-N

  36. How it works • How many? • One map/session • One map/table • One map/class • One map/inheritance tree • Map key? • Primary key in the data base if it is 1 column • Explicit vs. generic • findPerson(1) • find (“Person”, 1) Computer Science Department, TUC-N

  37. Implementation private Map people = new HashMap(); public static void addPerson(Person arg) { soleInstance.people.put(arg.getID(), arg); } public static Person getPerson(Long key) { return (Person)soleInstance.people.get(key); } Computer Science Department, TUC-N

  38. Concurrency Patterns • Multiple processes/threads that manipulate the same data • A solution -> Transaction managers…. as long as all data manipulation is within a transaction. • What if data manipulation spans transactions? Computer Science Department, TUC-N

  39. Concurrency problems • lost updates • inconsistent read • Correctness failure • liveness – how much concurrency can the system handle? Computer Science Department, TUC-N

  40. Execution contexts • “A request corresponds to a single call from the outside world which the software works on and optionally sends back a response” • “A session is a long running interaction between a client and server.” • “A process is a, usually heavyweight, execution context that provides a lot of isolation for the internal data it works on.” • “A thread is a lighter-weight active agent that's set up so that multiple threads can operate in a single process.” Computer Science Department, TUC-N

  41. Solutions • isolation: partition the data so that any piece of data can only be accessed by one active agent. • immutable data: separate the data that cannot be modified. • mutable data than cannot be isolated: • Optimistic Concurrency Control • Pessimistic Concurrency Control Computer Science Department, TUC-N

  42. Optimistic Concurrency Control • Conflict detection • Lock hold during commit • Supports concurrency • Low frequency of conflicts • Used for not critical consequences Computer Science Department, TUC-N

  43. Pessimistic Concurrency Control • Conflict prevention • Lock hold during the entire transaction • Does not suport concurrency • Used for critical consequences Computer Science Department, TUC-N

  44. Preventing inconsistent reads • Optimistic control • Versioning • Pessimistic control • Read ->shared lock • Write -> exclusive lock • Temporal reads • Data+time stamps • Implies full history storage Computer Science Department, TUC-N

  45. Deadlocks • Pick a victim • Locks with deadlines • Preventing: • Force to acquire all the necessary locks at the beginning • Enforce a strategy to grant locks (ex. Alphabetical order of the files) • Combine tactics Computer Science Department, TUC-N

  46. Transactions • ACID • Transactional resource (ex. Database) • Increase throughput -> short transactions • Transactions mapped on a single request • Late transactions -> read data first, start transaction for updates • Transactions spanning several requests -> long transactions • Lock escalation (row level -> table level) Computer Science Department, TUC-N

  47. Application Server Concurrency • process-per-session • Uses a lot of resources • process-per-request • Pooled processes • Sequential requests • Resources for a request should be released • thread-per-request • More efficient • No isolation Computer Science Department, TUC-N

  48. Concurrency Patterns • Optimistic Offline Lock • Pessimistic Offline Lock • Implicit Lock • Coarse-Grained Lock Computer Science Department, TUC-N

  49. Optimistic Offline Lock Prevent conflicts between concurrent business transactions, by detecting a conflict and rolling back the transaction. Computer Science Department, TUC-N

  50. Computer Science Department, TUC-N

More Related