Session 7: Introduction to Design and Architectural Patterns
Total Page:16
File Type:pdf, Size:1020Kb
Software Engineering G22.2440-001 Session 7 – Sub-Topic 5 Introduction to Design and Architectural Patterns Dr. Jean-Claude Franchitti New York University Computer Science Department Courant Institute of Mathematical Sciences 1 First Example A Dice Game A Player rolls 10x 2 dices If result = 7, score=score + 10 points At the end, score of the player is registred in the highscore table. 2 Activity Diagram menu [highscore] [start] [exit] view Start Highscore turn=0 Roll Dice turn++ [true] Turn<10 [false] Update highscore 3 Analysis Diagram… 4 Design Stage Manage User Interface Manage Persistence of highscore in a file or in relational database Realize a layered architecture : Apply the Layer Architectural Pattern 5 Layer Helps structure an application that can be decomposed into groups of subtasks in which each group of subtasks is at a particular level of abstraction. 6 Layer: examples 7 Layer :Structure 8 Layer: Structure 9 Layer and components… 10 Layers : Variants Relaxed Layered System: – A layer « j » can use service of j-1, j-2… – A layer can be partially opaque • Some service to layer j+1, others to all upper services… Layering through inheritance: – Lower layers are implemented as base classes – Higher level can override lower level… 11 Layers : Known Uses • Virtual machines: JVM and binary code format • API : Layer that encapsulates lower layers • Information System – Presentation, Application logic, Domain Layer, Database • Windows NT (relaxed for: kernel and IO and hardware) – System services, – Resource management (Object manager, security monitor, process manager, I/O manager, VM manager, LPC), – Kernel (exception handling, interrupt, multipro synchro, threads), – HAL (Hardware Abstraction Level) – Hardware 12 Layers: benefits Reuse of layers Support for standardization (POSIX) Dependencies are kept local Exchangeabilities : – Replacement of old implementation with Adapter Pattern – Dynamic exchange with Bridge Pattern 13 Layers: Liabilities Cascades of changing behavior Lower efficiency Unnecessary work: functions of a layer called many times for one service Difficulty of establishing correct granularity of layers: Too few layers -> less benefits, too many layers -> complexity and overhead… 14 Applying Layer Architecture UI Core Play View High Score Persistence Fichier ou BDD 15 Package decomposition <<layer>> UI <<layer>> <<subsystem>> Core Util <<layer>> Persist 16 Layer « core » Contain business logic classes… Adapt analysis classes for implementation Use of singleton Idiom… 17 Singleton (Idiom) Ensure a class only has one instance, and provide a global point of access to it. 18 Singleton Structure 19 Core « Layer »:First diagram Design Analysis 20 Util « subsystem » • Need for random numbers • Use java.util « random » functionality… • The random number generator is shared by the die… • Another singleton... Subsystem « util » Package decomposition <<layer>> UI <<layer>> <<subsystem>> Core Util <<layer>> Persist 23 Observer One-to-many dependency between objects: change of one object will automatically notify observers 24 Observer: Applicability A change to one object requires changing an unknown set of other objects Object should be able to notify other objects that may not be known at the beginning 25 Observer: Structure 26 Observer: Consequences Abstract coupling between subject and observer Support for broadcast communication Hard to maintain 27 Applying Observer Pattern 28 Observer View 29 Views are graphical objects 30 Setting up Observer : RollForm : : PlayerView : Die : DieView Playe 1: display( ) 2: PlayerView(Player) 3: addObserver(Observer) 4: return component 5: display() 6: DieView(Die) 7: addObserver(Observer) 8: return component 31 Observer : Change Propagation : Die : Randomizer : DieView : JLabel 1: getValue( ) 2: setValue(int) 3: notifyObservers( ) 4: update(Observable, Object) 5: getState() 3 6: setText(3) 32 UI/Core Separation... Layered Architecture... UI Decoupling classes and interfaces Core 34 MVC • Java AWT Java: Delegation Model – Event propagation from user interface to core application classes • MVC: – State change propagation to graphical objects Package decomposition <<layer>> UI <<layer>> <<subsystem>> Core Util <<layer>> Persist 36 Pattern Factory Method Intent – Define an interface for creating an object, but let sub-classes decide which class to instantiate – let a class defer instantiation to subclasses – Also known as Virtual Constructor 37 Factory Method Applicability : Use when – a class cannot anticipate the class of objects it must create – a class wants its subclasses to specify the objects it creates – classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass to delegate. 38 Structure 39 Factory method Consequences – Provide hooks for subclasses – connects parallel class hierarchies Known uses – MacApp, ET++ – ClassView in smalltalk80 MVC (controller creation) – Orbix ORB for generating PROXY object 40 « Persist » Layer Persistence technical classes Ensure independence of Core/Persist – Be able to switch « persistent engine » For example: – Persistence via « Serialization » – Persistence via a relational database (JDBC). 41 Applying Factory Abstract produc Concrete product Concrete Factory Abstract Factory 42 Applying Factory : DiceGame : SrKit : HighScoreSr : RealPlayer 1: SrKit( ) Attention! DiceGame voit SrKit comme un PersistKit et HighScoreSr 2: getInstance( ) comme un HighScore 3: DiceGame( ) 4: makeKit( ) 5: HighScoreSr( ) Seul le Realplayer sait qu'il utilise un SrKit ! DiceGame 6: load( ) non ! 7: quit( ) 8: getInstance( ) 9: save( ) 43 Using Serialization e1 : Entry • Persistence propagation... : High e2 : Entry Score e3 : Entry e4 : Entry A little bit of code…that’s all folks class HighScoreSr extends HighScore implements Serializable { ... public void save() throws Exception { FileOutputStream ostream = new FileOutputStream(filename); ObjectOutputStream p = new ObjectOutputStream(ostream); p.writeObject(this); // Write the tree to the stream. p.flush(); ostream.close(); // close the file. } public void load() throws Exception { FileInputStream istream = new FileInputStream(filename); ObjectInputStream q = new ObjectInputStream(istream); HighScoreSr hsr = (HighScoreSr)q.readObject(); } } JdbPersist... Dynamic Model • A table must be created in a relational DBMS • Upon creation of HighScoreJDBC: Connection to DBMS via JDBC • save: – Perform « inserts » for each « entry » • load: – Select * from ..., – Follow the result, – create « entry » objects A little bit of code... public class HighScoreJDBC extends HighScore { public static final String url="jdbc:odbc:dice"; Connection con=null; public HighScoreJDBC() { try { //loads the driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=DriverManager.getConnection(url, "molli",""); } catch (Exception e) { e.printStackTrace(); new Error("Cannot access Database at"+url); } hs=this; // register unique instance ! this.load(); } Jdbc Load public void load() { try { Statement select=con.createStatement(); ResultSet result=select.executeQuery ("SELECT Name,Score FROM HighScore"); while (result.next()) { this.add(new Entry(result.getString(1), result.getInt(2))); } } catch (Exception e) { e.printStackTrace(); } } Jdbc Save public void save() { try { for (Enumeration e = this.elements() ; e.hasMoreElements() ;) { Entry entry=(Entry)e.nextElement(); Statement s=con.createStatement(); s.executeUpdate( "INSERT INTO HighScore (Name,Score)"+ "VALUES('"+entry.getName()+"',"+ entry.getScore()+")"); } } catch (Exception e) { e.printStackTrace(); } } Summary • 1 Architectural pattern : Layer • 2 Design Patterns : Observer, Factory • 1 Idiom : Singleton • Pb: – Combining pattern to combine their forces… 50 51 Bank example… A basic bank system: – 1 bank, n Account. – Each account belong to 1 client. – Each account is credited by an amount a money. Bank functions – Withdrawal on an account, Credit an account, Transfer money from one account to another… 52 Naive solution 53 Naive Solution : c li e n t : B a n k 1 : Account 2 : Account transfer( 1,2,100 ) w ithdraw al(1,100 ) getAccount(1 ) w ithdraw( 100) deposit(2,100 ) getAccount(2 ) deposit( 100) 54 Applying Command Pattern… Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations. 55 Command Example 56 Command Example 57 Command Structure 58 Command Structure 59 Command Consequences n Command decouples the object that invokes the operation from the one that knows how to perform it. n Commands are first-class objects. They can be manipulated and extended like any other object. n It's easy to add new Commands, because you don't have to change existing classes. 60 Applying Command Pattern 61 Applying Command Pattern : client t : Transfer : Bank 1 : Account 2 : Account Transfer(1,2,100 ) Execute(t ) do( ) getAccount( 1) withdraw( 100) getAccount( 2) deposit( ) 62 Composite Pattern Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. 63 Composite Example 64 Composite Example 65 Composite Structure 66 Applying Composite on Command 67 Applying Composite 68 : client w : Withdrawal d : Deposit m : Macrocom : Bank 1 : Account 2 : Account Withdrawal(b, 1,100 ) Deposit(b,2,100 ) Macrocom(b ) add( w) add(d ) Execute(m ) do( ) do( ) getAccount( 1) withdraw( 100) do( ) getAccount(