Download presentation
Presentation is loading. Please wait.
Published byDaniela Horn Modified over 9 years ago
1
Spring 2009Computer Science Department, TUC-N Object Oriented Methods Architectural Patterns 3
2
Spring 2009Computer Science Department, TUC-N Content Patterns for Enterprise Application Architecture [Fowler] - continued –Data Source Patterns –Concurrency Patterns
3
Spring 2009Computer Science Department, TUC-N References Martin Fowler et. al, Patterns of Enterprise Application Architecture, Addison Wesley, 2003 [Fowler]
4
Spring 2009Computer 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
5
Spring 2009Computer 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
6
Spring 2009Computer 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.
7
Spring 2009Computer Science Department, TUC-N TDG
8
Spring 2009Computer 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
9
Spring 2009Computer Science Department, TUC-N Using ADO.NET DataSets
10
Spring 2009Computer 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;} }
11
Spring 2009Computer 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;}
12
Spring 2009Computer 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); }
13
Spring 2009Computer 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’
14
Spring 2009Computer Science Department, TUC-N Row Data Gateway
15
Spring 2009Computer 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 ?
16
Spring 2009Computer 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.
17
Spring 2009Computer Science Department, TUC-N RDG behavior
18
Spring 2009Computer 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() { …} …
19
Spring 2009Computer 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); }
20
Spring 2009Computer 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.getNumberOfDepend ents())); result.append("\n"); } return result.toString();
21
Spring 2009Computer 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(); }
22
Spring 2009Computer 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
23
Spring 2009Computer 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.
24
Spring 2009Computer Science Department, TUC-N How it works – retrieving data
25
Spring 2009Computer Science Department, TUC-N Finding objects
26
Spring 2009Computer Science Department, TUC-N How it works – updating data
27
Spring 2009Computer Science Department, TUC-N Features Independent database schema and object model Extra layer Works well with Domain Model
28
Spring 2009Computer 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)
29
Spring 2009Computer 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); }
30
Spring 2009Computer 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); } }
31
Spring 2009Computer 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;
32
Spring 2009Computer 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); }
33
Spring 2009Computer Science Department, TUC-N Separating finders
34
Spring 2009Computer Science Department, TUC-N Hybrid Data Source Patterns Active Record = RDG + Domain Logic. Table Module ≈ TDG + Domain Logic. –TDG like module that processes ResultSets.
35
Spring 2009Computer 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
36
Spring 2009Computer 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)
37
Spring 2009Computer 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); }
38
Spring 2009Computer 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?
39
Spring 2009Computer Science Department, TUC-N Concurrency problems lost updates inconsistent read Correctness failure liveness – how much concurrency can the system handle?
40
Spring 2009Computer 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.”
41
Spring 2009Computer 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
42
Spring 2009Computer Science Department, TUC-N Optimistic Concurrency Control Conflict detection Lock hold during commit Supports concurrency Low frequency of conflicts Used for not critical consequences
43
Spring 2009Computer Science Department, TUC-N Pessimistic Concurrency Control Conflict prevention Lock hold during the entire transaction Does not suport concurrency Used for critical consequences
44
Spring 2009Computer 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
45
Spring 2009Computer 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
46
Spring 2009Computer 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)
47
Spring 2009Computer 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
48
Spring 2009Computer Science Department, TUC-N Concurrency Patterns Optimistic Offline Lock Pessimistic Offline Lock Implicit Lock Coarse-Grained Lock
49
Spring 2009Computer Science Department, TUC-N Optimistic Offline Lock Prevent conflicts between concurrent business transactions, by detecting a conflict and rolling back the transaction.
50
Spring 2009Computer Science Department, TUC-N
51
Spring 2009Computer Science Department, TUC-N How it works Associate a version number to each record When a record is loaded the session state contains the version number Getting the lock = comparing the versions If lock aquired -> transaction committed, version number incremented
52
Spring 2009Computer Science Department, TUC-N Update optimistic check
53
Spring 2009Computer Science Department, TUC-N Analysis Versioning on UPDATE and DELETE does not prevent inconsistent reads Add versions on items that need to be checked does not provide adequate solutions for some of the trickier concurrency and temporal issues
54
Spring 2009Computer Science Department, TUC-N Pessimistic Offline Lock Prevent conflicts between concurrent business transactions by allowing only one business transaction to access data at once.
55
Spring 2009Computer Science Department, TUC-N
56
Spring 2009Computer Science Department, TUC-N How it works To implement it you need to: –know what type of locks you need, –build a lock manager, –define procedures for a business transaction to use locks Lock types –Exclusive write lock –Exclusive read lock –Read/write lock Read and write locks are mutually exclusive. Concurrent read locks are acceptable
57
Spring 2009Computer Science Department, TUC-N Lock manager The lock manager's job is to grant or deny any request by a business transaction to acquire or release a lock A table that maps locks to owners Protocol of Business transaction to use the lock manager –what to lock, –when to lock, –when to release a lock, –how to act when a lock cannot be acquired.
58
Spring 2009Computer Science Department, TUC-N Protocol [when?] acquire a lock before loading the data [what?] objects (id) or records (primary key) [when to release?] release locks when the business transaction completes [what if acquiring fails?] abort
59
Spring 2009Computer Science Department, TUC-N Analysis Access to the lock table must be serialized Performance bottleneck Consider granularity (Coarse grained lock) Possible deadlocks Lock timeout for lost sessions
60
Spring 2009Computer Science Department, TUC-N Implicite lock Allow framework code to acquire offline locks
61
Spring 2009Computer Science Department, TUC-N How it works if an item might be locked anywhere it must be locked everywhere Factor your code such that any locking mechanics that absolutely cannot be skipped can be carried out by your application framework
62
Spring 2009Computer Science Department, TUC-N How it works Optimistic lock –store a version count for each record, –include the version in update SQL criteria, –store an incremented version when changing the record Pessimistic Lock –acquiring any lock necessary to load a piece of data –release of all locks when the business transaction or session completes –assure that a write lock has already been obtained before committing any changes
63
Spring 2009Computer Science Department, TUC-N Coarse-Grained Lock Lock a set of related objects with a single lock
64
Spring 2009Computer Science Department, TUC-N How it works create a single point of contention for locking a group of objects Optimistic Lock –shared version
65
Spring 2009Computer Science Department, TUC-N Root lock Navigation issues -> Lazy load
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.