elaboration iteration 3 – part 3 - persistence framework -

24
OO Methodology Elaboration Iteration 3 – Part 3 - Persistence Framework -

Upload: owen-stephens

Post on 08-Jan-2018

222 views

Category:

Documents


0 download

DESCRIPTION

Table of Contents Iteration 1 Iteration 2 Iteration 3 Use-Case Model Process Sale Use Case Domain Model Design Model Iteration 2 GRASP: More Patterns for Assigning Responsibilities Designing Use-Case Realizations with GoF Design Patterns Iteration 3 Related Use Cases Modeling Generalization Refining the Domain Model Adding New SSDs and Contracts Modeling Behavior in Statechart Diagrams Designing the Logical Architecture with Patterns Organizing the Design and Implementation Model Packages Introduction to Architectural Analysis and the SAD Designing More Use-Case Realization with Paterns Designing a Persistence Framework with Patterns

TRANSCRIPT

Page 1: Elaboration Iteration 3 – Part 3 - Persistence Framework -

OO Methodology

Elaboration Iteration 3 – Part 3- Persistence Framework -

Page 2: Elaboration Iteration 3 – Part 3 - Persistence Framework -

2

Table of Contents

• Iteration 1– Use-Case Model– Process Sale Use Case– Domain Model– Design Model

• Iteration 2 – GRASP: More Patterns for Assigning Responsibilities– Designing Use-Case Realizations with GoF Design Patterns

• Iteration 3– Related Use Cases– Modeling Generalization– Refining the Domain Model– Adding New SSDs and Contracts– Modeling Behavior in Statechart Diagrams– Designing the Logical Architecture with Patterns– Organizing the Design and Implementation Model Packages– Introduction to Architectural Analysis and the SAD– Designing More Use-Case Realization with Paterns– Designing a Persistence Framework with Patterns

Page 3: Elaboration Iteration 3 – Part 3 - Persistence Framework -

3

Iteration 3 Requirements

• Provide failover to local services when the remote services cannot be accessed.

• Provide support for POS device handling, such as the cash drawer and coin dispenser

• Handle credit payment authorization• Support for persistent objects

Page 4: Elaboration Iteration 3 – Part 3 - Persistence Framework -

4

Designing a Persistence Framework

• Objectives– Design part of a framework with the Template Method, State,

and Command patterns– Introduce issues in object-relational(O-R) mapping– Implement lazy materialization with Virtual Proxies

• Requirements– the NextGen application requires storing and retrieving

information in a persistent storage mechanism, such as relational database (e.g. ProductSpefication )

• Persistent Objects– objects that require persistent storage

• Solution– a persistence service from a persistence framework– a persistence framework is a general, reusable, and

extendable set of types that provides functionality to support persistent objects

– Persistence service is usually written to work with RDB (O-R mapping service)

– In terms of the layered architecture, a persistence service is a subsystem within the technical service layer

Page 5: Elaboration Iteration 3 – Part 3 - Persistence Framework -

5

Frameworks

• is a cohesive set of interfaces and classes that collaborate to provide services for the core, unvarying part of a logical subsystem

• contains concrete and abstract classes that define interfaces to conform to, object interactions to participate in, and other invariants

• usually requires the framework user to define subclasses of existing framework classes to make use of, customize, and extend the framework services

• relies on the Hollywood Principle – “don’t call us, we’ll call you”

Page 6: Elaboration Iteration 3 – Part 3 - Persistence Framework -

6

Persistence Framework

• Requirements– store and retrieve objects in a persistent storage mechanism– commit and rollback transactions

• Key Ideas– Mapping

• mapping between a class and its persistent store(table), and between object attributes and the fields in a record

– Object Identity• To easily relate records to objects, and to ensure there are no

inappropriate duplicates– Database Mapper

• responsible for materialization and dematerialization– Materialization and Dematerialization

• materialization is to transform a non-object representation into objects

– Caches– Transaction State of Object

• the state of objects in terms of their relationship to the current transactions

– Transaction Operations• commit, rollback

– Lazy Materialization• materialized on demand

– Virtual Proxies• lazy materialization can be implemented using a smart reference

known as a virtual proxy

Page 7: Elaboration Iteration 3 – Part 3 - Persistence Framework -

7

Representing Objects as Tables

• How to map an object to a record – define a table in a RDB for each persistent object class– object attributes containing primitive data types mat to

columns

• UML Data Modeling Profile– a coherent set of UML stereotypes, tagged values, and

constraints for modeling RDB

«Table»ProductSpecification

«PK» OID : char(16)Description : varchar(100)...«FK» Manu_OID : char(16)

«Table»Manufacturer

«PK» OID : char(16)Name : varchar(100)City : varchar(50)

*1

aggregate signifies a referential constraint: a ProductSpecificationrow can't exist without a related Manufacturer row

PK - primary keyFK - foreign key

Manufacturer

namecity...

...

name city

Now&Zen Mumbai

MANUFACTURER TABLE: Manufacturer

name = Now&Zencity = Mumbai

CelestialShortening San Ramon

Page 8: Elaboration Iteration 3 – Part 3 - Persistence Framework -

8

Object Identifier

• Consistent way to relate objects to records– Assign an object identifier(OID) to each record and object

• OID– an alphanumeric value– unique to a specific object– within in objects, an OID is represented by OID interface or

class, and in RDB OID is stored as a character string

OID

xyz123

abc345

This is a simplified design.In reality, the OID may beplaced in a Proxy class.

primary key

Manufacturer

citynameoid : OID...

...

name city

Now&Zen Mumbai

MANUFACTURER TABLE: Manufacturer

city = Mumbainame = Now&Zenoid = xyz123

CelestialShortening San Ramon

Page 9: Elaboration Iteration 3 – Part 3 - Persistence Framework -

9

Accessing Persistence Service

• Facade to Persistence Subsystem– a unified interface to persistence subsystem– DB Adapter collaborates with Persistence Facade

1PersistenceFacade

...

getInstance() : PersistenceFacade

get( OID, Class ) : Objectput( OID, Object )...

: DBProductsAdapter «singleton»: PersistenceFacade

obj :=get(...)

// example use of the facade

OID oid = new OID("XYZ123");ProductSpecification ps = (ProductSpecification) PersistenceFacade.getInstance().get( oid, ProductSpecification.class );

IProductsAdapter

Page 10: Elaboration Iteration 3 – Part 3 - Persistence Framework -

10

Mapping Objects: Database Mapper

• Who should be responsible for materialization and dematerialization of objects

– persistent object itself by Information Expert (direct mapping)

• strong coupling of the persistent object class to persistent storage knowledge

– using Database Mapper (indirect mapping)• Database Mapper

– a different mapper class is defined for each persistent object class

each mapper gets and puts objects in its own unique way,depending on the kind of data store and format

1PersistenceFacade

getInstance() : PersistenceFacade

get( OID, Class ) : Objectput( OID, Object )...

ProductSpecificationRDBMapper

...

get( OID) : Objectput( OID, Object )...

ProductSpecificationFlatFileMapper

...

get( OID) : Objectput( OID, Object )...

ManufacturerRDBMapper

...

get( OID) : Objectput( OID, Object )...

note that the Class as aparameter is no longerneeded in this version ofget, as the class is"hardwired" for a particularpersistent type

1

«interface»IMapper

get(OID) : Objectput( OID, Object )...

Class

UML notation: This is a qualified assocation. It means:

1. There is a 1-M association from PersistenceFacade to IMapper objects.2. With a key of type Class, an IMapper is found (e.g., via a HashMap lookup)

Page 11: Elaboration Iteration 3 – Part 3 - Persistence Framework -

11

Framework Design with Template Method Pattern

• Template Method– define the skeleton of an algorithm in a method(template

method), with some varying and unvarying parts, deffering some steps to subclasses.

– template method invokes other methods, some of which may be overridden in a subclass(hook method)

AbstractClass

templateMethod()

primitiveOperation()

concreteOperation()

ConcreteClass

primitiveOperation()

templateMethod{ ... primitiveOperation() ... concreteOperation() ...}

Template Method (GoF pattern)

defines skeleton of an algorithm,with varying and unvarying parts

abstract primitive operations

- varying part- overriden in subclass

concrete operations

- default behavior- if can be overriden in subclass, then is called a hook method

Page 12: Elaboration Iteration 3 – Part 3 - Persistence Framework -

12

An Application of Template Method

• Painting in GUI Framework

GUIComponent

update()

repaint()

MyExcellentButton

repaint()

// this is the template method// its algorithm is the unvarying part

public void update(){ clearBackground();

// this is the hook method // it is the varying part repaint();}

hook method

- varying part- overriden in subclass-may be abstract, or have a default implementation

hook method overriden

- fills in the varying part ofthe algorithm

HOLLYWOOD PRINCIPLE:Don't call us, we'll call you

Note that the MyExcellentButton--repaint methodis called from the inherited superclass updatemethod. This is typical in plugging into aframework class.

FRAMEWORK class

OUR class

template method

hook method

Page 13: Elaboration Iteration 3 – Part 3 - Persistence Framework -

13

Materialization with Template Method

• Skeleton algorithm for get method in AbstractMapperif (object in cache) return itelse create the object from its representation in storage save object in cache return it

AbstractPersistenceMapper

+ get( OID) : Object {leaf}

# getObjectFromStorage(OID) : Object {abstract}...

«interface»IMapper

get(OID) : Objectput( OID, Object )...

{// template methodpublic final Object get( OID oid ){obj := cachedObjects.get(oid); if (obj == null ) { // hook method obj = getObjectFromStorage( oid );

cachedObjects.put( oid, obj ); }return obj;}}

UML notation:

{leaf} is used for final orleaf operations andclasses.

# means "protected";only visible to subclasses

HOOK

TEMPLATE

Page 14: Elaboration Iteration 3 – Part 3 - Persistence Framework -

14

Materialization with Template Method

• Overriding the hook method

ProductSpecificationRDBMapper

# getObjectFromStorage(OID) : Object

AbstractPersistenceMapper

+ get( OID) : Object {leaf}

# getObjectFromStorage(OID) : Object{abstract}...

{// template methodpublic final Object get( OID oid ){obj := cachedObjects.get(oid); if (obj == null ) { // hook method obj = getObjectFromStorage( oid );

cachedObjects.put( oid, obj ) }return obj}}

{// hook method overrideprotected Object getObjectFromStorage( OID oid ){String key = oid.toString();dbRec = SQL execution result of: "Select * from PROD_SPEC where key =" + key

ProductSpecification ps = new ProductSpecification();ps.setOID( oid );ps.setPrice( dbRec.getColumn("PRICE") );ps.setItemID( dbRec.getColumn("ITEM_ID") );ps.setDescrip( dbRec.getColumn("DESC") );

return ps;}}

IMapper

Page 15: Elaboration Iteration 3 – Part 3 - Persistence Framework -

15

Materialization with Template Method

• getObjectFromStorage hook method is also a candidate template method

AbstractRDBMapper

tableName : String

+ «constructor» AbstractRDBMapper( tableName )

# getObjectFromStorage(OID) : Object {leaf}

# getObjectFromRecord(OID, DBRecord) : Object {abstract}

- getDBRecord(OID) : DBRecord

AbstractPersistenceMapper

+ get( OID) : Object {leaf}

# getObjectFromStorage(OID) : Object {abstract}...

{protected final Object getObjectFromStorage( OID oid ){dbRec = getDBRecord( oid ); // hook methodreturn getObjectFromRecord( oid, dbRec );}}

IMapper

ProductSpecificationRDBMapper

+ «constructor» ProductSpecificationRDBMapper(tabName)

# getObjectFromRecord(OID, DBRecord) : Object

{// hook method overrideprotected Object getObjectFromRecord( OID oid, DBRecord dbRec ){ProductSpecification ps = new ProductSpecification();ps.setOID( oid );ps.setPrice( dbRec.getColumn("PRICE") );ps.setItemID( dbRec.getColumn("ITEM_ID") );ps.setDescrip( dbRec.getColumn("DESC") );

return ps;}}

{private DBRecord getDBRecord OID oid ){String key = oid.toString();dbRec = SQL execution result of: "Select * from "+ tableName + " where key =" + key return dbRec;}}

Page 16: Elaboration Iteration 3 – Part 3 - Persistence Framework -

16

Persistence Framework

1

«interface»IMapper

get(OID) : Objectput( OID, Object )...

Class

1+ PersistenceFacade

getInstance() : PersistenceFacade

get( OID, Class ) : Objectput( OID, Object )...

AbstractPersistenceMapper

+ get( OID) : Object {leaf}# getObjectFromStorage(OID) : Object...

AbstractRDBMapper

+ AbstractRDBMapper(tableName)# getObjectFromStorage(OID) : Object {leaf}# getObjectFromRecord(OID, DBRecord) : Object- getDBRecord(OID) : DBRecord

Persistence

NextGen Persistence

ProductSpecificationRDBMapper

+ ProductSpecificationRDBMapper(tableName)# getObjectFromRecord(OID, DBRecord) : Object

ProductSpecificationFileWithXMLMapper

# getObjectFromStorage(OID) :Object

SaleRDBMapper

...# getObjectFromRecord(OID, DBRecord) : Object

ProductSpecificationInMemoryTestDataMapper

# getObjectFromStorage(OID) :Object

Page 17: Elaboration Iteration 3 – Part 3 - Persistence Framework -

17

Configuring Mappers with a MapperFactory

– a solutinto get each mapper with a different operation within the Factory

class MapperFactory{ public IMapper getProduct SpecificationMapper() {...} public IMapper getsalemapper() { ... } ...} violate Protected Variations

– better solutionusing data-driven, factory assign a set of IMappersclass MapperFactory{ public Map getAllMappers() { ... }}

class PersistenceFacade{ private java.util.Map mappers = MapperFactory.getInstance().getAllMappers(); public Object get(OID oid, class persistenceClass) { IMapper mapper = (IMapper) mappers.get(persistenceclass); return mapper.get(oid); }}

Page 18: Elaboration Iteration 3 – Part 3 - Persistence Framework -

18

Transaction States and the State Pattern

• Transaction– persistent objects can be inserted, deleted, or modified– operating on a persistent object does not cause an immediate

database update, rather an explicit commit operation must be performed

OldClean OldDirty

OldDelete

commit /delete

delete

New

[ from DB][new (not from DB)]

save

commit /update

delete

rollback /reload

rollback /reload

commit /insert

State chart: PersistentObject

Legend:New--newly created; not in DBOld--retrieved from DBClean--unmodifiedDirty--modified

Deleted

Page 19: Elaboration Iteration 3 – Part 3 - Persistence Framework -

19

Context for State Pattern

• Common technical services

• Repeating case logic structure

Persistence

Domain

ProductSpecification

... PersistentObjectoid : OIDtimeStamp:DateTimecommit()delete()rollback()save()...

public void commit(){switch (state){ case OLD_DIRTY: //... break; case OLD_CLEAN: //... break; ...}}

public void rollback(){switch (state){ case OLD_DIRTY: //... break; case OLD_CLEAN: //... break; ...}}

Page 20: Elaboration Iteration 3 – Part 3 - Persistence Framework -

20

State Pattern

• Context/Problem– An object’s behavior is dependent on its state, and its

methods contain case logic reflecting conditional state-dependent actions.

• Solution– Create state classes for each state, implementing a common

interface. Delegate state-dependent operations from the context object to its current state object.

Page 21: Elaboration Iteration 3 – Part 3 - Persistence Framework -

21

Applying State Pattern

PersistentObject

oid : OIDstate : PObjectState

commit()delete()rollback()save()setState(PObjectState)...

PObjectState

commit(obj : PersistentObject)delete(obj : PersistentObject)rollback(obj : PersistentObject)save(obj : PersistentObject)

OldDirtyState

commit(...)delete(...)rollback(...)

1

OldCleanState

delete(...)save(...)

NewState

commit(...)

OldDeleteState

commit(...)rollback(...)

ProductSpecification

...

...

Sale

...

...

*

{ state.delete( this ) }

{ // default no-op // bodies for // each method}

{ // deleteobj.setState( OldDeleteState.getInstance() ) }

{ // saveobj.setState( OldDirtyState.getInstance() ) }

{ // rollbackPersistenceFacade.getInstance().reload( obj )obj.setState( OldCleanState.getInstance() ) }

{ // commitPersistenceFacade.getInstance().update( obj )obj.setState( OldCleanState.getInstance() ) }

{ state.rollback( this ) } { state.commit( this ) }{ state.save( this ) }

{ // commitPersistenceFacade.getInstance().insert( obj )obj.setState( OldCleanState.getInstance() ) }

{ // commitPersistenceFacade.getInstance().delete( obj )obj.setState( DeletedState.getInstance() ) }

Page 22: Elaboration Iteration 3 – Part 3 - Persistence Framework -

22

Designing a Transaction with the Command Pattern

• Transaction is a set of tasks that must all complete successfully, or none must be completed. (atomic)

– the tasks of a transaction include inserting, updating, deleting objects.

– e.g. a transaction can contain two inserts, one update, and three deletes.

• Transaction – is a good candidate class– contains tasks– tasks can be queued, and delayed for execution, reordered for

performance, integrity, etc.

• Command Pattern– Context/Problem

• How to handle requests or tasks that need functions such as sorting, queueing, delaying, logging, or undoing?

– Solution• Make each task a class that implements a common interface

– Example• GUI actions should be stacked and can be undoed• server-side handles client requests by queueing, prioritizing,

executing them

Page 23: Elaboration Iteration 3 – Part 3 - Persistence Framework -

23

Designing a Transaction with the Command Pattern

• Commands for database operations

«interface»ICommand

execute( )undo()

DBInsertCommand

execute()

DBUpdateCommand

execute()

DBDeleteCommand

execute()

Transaction

commands : List

commit()addDelete(obj:PersistentObject)addInsert( obj:PersistentObject)addUpdate( obj:PersistentObject)sort()...

1..*

DBCommand

object : PersistentObject

execute() {abstract}undo() {leaf}

undo is a no-op forthis example, but amore complexsolution adds apolymorphic undoto each subclasswhich uniquelyknows how to undoan operation

PersistentObject

commit()...

1

11{commands.add( new DBUpdateCommand(obj) );}

use SortStrategy objects to allowdifferent sort algorithms to order theCommands

perhaps simply object.commit()but each Command canperform its own uniqueactions

{sort()for each ICommand cmd cmd.execute()}

Page 24: Elaboration Iteration 3 – Part 3 - Persistence Framework -

24

Lazy Materialization with a Virtual Proxy

• It is sometimes desirable to defer the materialization of an object until it absolutely required, for performance

• Virtual Proxy – is a proxy for another object that materializes the real subject

when it is first referenced– is a lightweight object that stands for a real object

ManufacturerProxy

realSubject : IManufacturer

- getRealSubject() : IManufacturer

+ getAddress()...

Manufacturer

address

getAddress()...

«interface»IManufacturer

getAddress()...

Proxy-for

1*realSubjec

t

{return getRealSubject().getAddress()}

ProductSpecification

manufacturer : IManufacturer...

getManufacturerAddress() : Address

1

{if ( realSubject == null ) realSubject = PersistenceFacade.get(oid, Manufacturer.class);return realSubject;}

PersistentObject

oid

...

1

{return manufacturer.getAddress()}

actually references aninstance ofManufacturerProxy

1

23