650 likes | 664 Views
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].
E N D
Object Oriented Methods Architectural Patterns 3 Computer Science Department, TUC-N
Content • Patterns for Enterprise Application Architecture [Fowler] - continued • Data Source Patterns • Concurrency Patterns Computer Science Department, TUC-N
References • Martin Fowler et. al, Patterns of Enterprise Application Architecture, Addison Wesley, 2003 [Fowler] Computer Science Department, TUC-N
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
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
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
TDG Computer Science Department, TUC-N
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
Using ADO.NET DataSets Computer Science Department, TUC-N
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
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
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
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
Row Data Gateway Computer Science Department, TUC-N
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
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
RDG behavior Computer Science Department, TUC-N
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
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
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
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
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
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
How it works – retrieving data Computer Science Department, TUC-N
Finding objects Computer Science Department, TUC-N
How it works – updating data Computer Science Department, TUC-N
Features • Independent database schema and object model • Extra layer • Works well with Domain Model Computer Science Department, TUC-N
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
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
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
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
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
Separating finders Computer Science Department, TUC-N
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
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
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
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
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
Concurrency problems • lost updates • inconsistent read • Correctness failure • liveness – how much concurrency can the system handle? Computer Science Department, TUC-N
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
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
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
Pessimistic Concurrency Control • Conflict prevention • Lock hold during the entire transaction • Does not suport concurrency • Used for critical consequences Computer Science Department, TUC-N
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
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
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
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
Concurrency Patterns • Optimistic Offline Lock • Pessimistic Offline Lock • Implicit Lock • Coarse-Grained Lock Computer Science Department, TUC-N
Optimistic Offline Lock Prevent conflicts between concurrent business transactions, by detecting a conflict and rolling back the transaction. Computer Science Department, TUC-N