1 What is Design? Developing a blueprint (plan) for a mechanism that performs the required task, … taking into account all the constraints, & … making trade-offs between constraints when they are in conflict. Design Levels • Architectural design . . . • Detailed design . . . • Implementation (executable designs) What is OO Analysis and Design • Object-Oriented Analysis – Important domain concepts or objects? – Vocabulary? – Visualized in the UP Domain Model • Object-Oriented Design – Design of software objects – Responsibilities – Collaborations – Design patterns – Visualized in the UP Design Model Larman’s Design Process Operation: enterItem(…) Post-conditions: – . . . Operation Contracts Sale date . . . Sales LineItem quantity 1 1..* . . . . . . Domain Model Use-Case Model Design Model : Register enterItem (itemID, quantity) : ProductCatalog d = getProductDescription(itemID) addLineItem( d, quantity ) : Sale Requirements Business Modeling Design Sample UP Artifact Relationships : System enterItem (id, quantity) Use Case Text System Sequence Diagrams make NewSale() system events Cashier Process Sale : Cashier use case names system operations Use Case Diagram Supplementary Specification Glossary starting events to design for, and detailed postcondition to satisfy Process Sale 1. Customer arrives … 2. … 3. Cashier enters item identifier. inspiration for names of some software domain objects functional requirements that must be realized by the objects ideas for the postconditions Register … makeNewSale() enterItem(…) … ProductCatalog … getProductDescription(…) … 1 * non-functional requirements domain rules item details, formats, validation Design Model : Register enterItem (itemID, quantity) : ProductCatalog spec = getProductSpec( itemID ) Requirements Business Modeling Design Sample UP Artifact Relationships Vision Glossary The logical architecture is influenced by the constraints and non-functional requirements captured in the Supp. Spec. Domain Model * * Supplementary Specification Use-Case Model Register … makeNewSale() enterItem(…) … ProductCatalog … getProductSpec(…) … class diagrams 1 1 (a static view) interaction diagrams (a dynamic view) UI package diagrams of the logical architecture (a static view) Domain Tech Services Design Model Domain Model Register id Item Store name address Sale dateTime / total CashPayment amountTendered Sales LineItem quantity Cashier id Customer Product Catalog Product Description itemID description price Stocks * Houses 1..* Used-by * Contains 1..* Describes * Captured-on Contained-in 1..* Records-sale-of 0..1 Paid-by Is-for Logscompleted * Works-on 1 1 1 1 1..* 1 1 1 1 1 1 1 0..1 1 1 Ledger Recordsaccountsfor 1 1 Use Case Model Requirements Partial artifacts, refined in each iteration. Use-Case Model text use cases :System foo( x ) system operation contracts system sequence diagrams bar( y ) use case diagrams system operations Logical Architecture – Simple Layers Domain UI Swing not the Java Swing libraries, but our GUI classes based on Swing Web Sales Payments Taxes Technical Services Persistence Logging RulesEngine Logical Architecture – Layers UI (AKA Presentation, View) Application (AKA Workflow, Process, Mediation, App Controller) Domain (AKA Business, Application Logic, Model) Technical Services (AKA Technical Infrastructure, High-level Technical Services) Foundation (AKA Core Services, Base Services, Low-level Technical Services/Infrastructure) width implies range of applicability GUI windows reports speech interface HTML, XML, XSLT, JSP, Javascript, … handles presentation layer requests workflow session state window/page transitions consolidation/transformation of disparate data for presentation handles application layer requests implementation of domain rules domain services (POS, Inventory) – services may be used by just one application, but there is also the possibility of multi-application services (relatively) high-level technical services and frameworks Persistence, Security low-level technical services, utilities, and frameworks data structures, threads, math, file, DB, and network I/O more app specific dependency Business Infrastructure (AKA Low-level Business Services) very general low-level business services used in many business domains CurrencyConverter Logical Architecture – Layers & Partitions Persistence Security Logging Technical Services POS Inventory Tax Domain Vertical Layers Horizontal Partitions Logical Architecture – Layers & Partitions Domain(s) Technical Services Foundation MySQL Inventory Persistence Naming and Directory Services Web AppFramework Technical Services POS Inventory Domain(s) Foundation Worse mixes logical and deployment views Better a logical view a logical representation of the need for data or services related to these subdomains, abstracting implementation decisions such as a database. 玞omponent? Novell LDAP UML notation: A UML component, or replaceable, modular part of the physical system UML notation: A physical database in the UML. Domain Model and Domain Layer Low representational gap Payment amount Sale date time Pays-for Payment amount: Money getBalance(): Money Sale date: Date startTime: Time getTotal(): Money . . . Pays-for UP Domain Model Stakeholder’s view of the noteworthy concepts in the domain. Domain layer of the architecture in the UP Design Model The object-oriented developer has taken inspiration from the real world domain in creating software classes. Therefore, the representational gap between how stakeholders conceive the domain, and its representation in software, has been lowered. 1 1 1 1 A Payment in the Domain Model is a concept, but a Payment in the Design Model is a software class. They are not the same thing, but the former inspired the naming and definition of the latter. This reduces the representational gap. This is one of the big ideas in object technology. inspires objects and names in SSDs, System Operations & Layers Domain UI Swing ProcessSale Frame … … Register makeNewSale() enterItem() … : Cashier makeNewSale() enterItem() endSale() makeNewSale() enterItem() endSale() enterItem(id, quantity) :System : Cashier endSale() description, total makeNewSale() the system operations handled by the system in an SSD represent the operation calls on the Application or Domain layer from the UI layer Design Objects Spend plenty of time on dynamic models (see notation chapter 15) Model-View Separation Principle (MVC) UI layer has views Domain layer has model Domain UI Swing not the Java Swing libraries, but our GUI classes based on Swing Web Sales Payments Taxes Technical Services Persistence Logging RulesEngine Model-View-Control Architecture (MVC) • MVC is an acronym for Model View Controller • It represents a software design pattern developed at Xerox PARC in 1978 (!) • It explains a method of separating the visual, interaction and data components. • Very popular, used extensively in Java and other languages Model-View-Control Architecture (MVC) Model • maintains the state and data of the application – the XML document View • A rendering of the XML document Controller • The user interface presented to the user to manipulate the application Why use MVC • Makes it very easy to have multiple different displays of the same information. • For example: a graph and a table could both display and edit the same data. • Essentially provides greater control over the UI and it’s behaviour. MVC Model • The “Model” contains the data • Has methods to access and possibly update it’s contents. • Often, it implements an interface which defines the allowed model interactions. • Implementing an interface enables models to be pulled out and replaced without programming changes. MVC Controller • Users interact with the controller. • It interprets mouse movement, clicks, keystrokes, etc • Communicates those activities to the model – eg: delete row, insert row, etc • It’s interaction with the model indirectly causes the View(s) to update MVC View • The View provides a visual representation of the model. • There can be multiple views displaying the model at any one time. • For example, a companies finances over time could be represented as a table and a graph. • These are just two different views of the same data. • When the model is updated, all Views are informed and given a chance to update themselves. Father’s MVC — The original • Application software was very close to underlying hardware. • View and controller would exist as a pair. View part of the pair would show user output and controller part of the pair would receive inputs from the user. Age of Modern Desktop Architectures • Most of the Controller functionality was taken care by the Operating System.It was no longer necessary for Controllers to listen to input devices. The idea of View object changed. • View became bi-directional in a sense it responds to user actions as well as displays the Model data. MVP • The Presenter oversees the presentation logic. The presenter can change the view directly. View delegates user events to the Presenter. • Depending on the implementation, View subscribes to the Model and relies on Presenter for complex logic or in other case, View simply relies on Presenter for everything. MVVM • MVVM is very similar to Passive View MVP but with an added twist of data binding. • It is a programming technique that binds data sources from the provider and consumer together and synchronizes them. • It gets rid of lots of boilerplate code that we traditionally need to keep View and Model in sync. Web MVC • The major confusion in the community is because of the unawareness that desktop MVC and web MVC are two different patterns. Only if web MVC would have been named something else, things would have been much clearer. Server-side MVC a.k.a. Model 2 • First well-known implementation of Serverside MVC is the Model 2 by Sun Microsystems for Java web applications. Going beyond the Server-side • Almost every browser started shipping JavaScript engines, it was the AJAX that changed the course of web applications. • This is the world of server-side MVC generating HTML + JavaScript. • JavaScript is mostly used to improve UX by reducing Server View Cycles. Things like form submission, input validation, etc. is handled by client-side code. Essential RIA — Rich Internet Application Architecture • RIA or Rich Web Applications are the category of applications where an application depends heavily on client-side code and their UX is very close to that of a desktop application. • It is mostly built using frameworks that supports SPA -Single Page Application. • There is usually just one initial HTML page and then client-side code and routing solutions are used to render subsequent pages. Essential RIA — Rich Internet Application Architecture • Back-end is mostly API driven. • View is confined to producing JSON and Controller is responsible for orchestration of the incoming requests and mapping them to appropriate business workflow. • Building RIA is a complex operation and has evolved from the learning of previous desktopbased GUI architectures. ViewModel, Observers, Components, etc. are some of the things that are borrowed from these architectures. Jacobson’s Objectory Design Objects Jacobson’s Objectory Design Objects Robustness model has • Entity objects • Boundary (interface objects) • Control objects Essentially UML collaboration (communication) diagram Jacobson’s Robustness Analysis Bridges Analysis-Design Gap Traceability Responsibility-Driven Design (RDD) • Detailed object design is usually done from the point of view of the metaphor of: – Objects have responsibilities – Objects collaborate • Responsibilities are an abstraction. – The responsibility for persistence. • Large-grained responsibility. – The responsibility for the sales tax calculation. • More fine-grained responsibility. The 9 GRASP Principles 1. Creator 2. Expert 3. Controller 4. Low Coupling 5. High Cohesion 6. Polymorphism 7. Pure Fabrication 8. Indirection 9. Protected Variations Object Responsibilities • A responsibility is an obligation of an object in terms of its behavior. • (More on this later) Design: Larman’s Approach • Methodology based on – Responsibility assignment. – GRASP General Responsibility Assignment Software Patterns. • Input: – Use cases. – Domain model. – Operation contracts. • Larman, Chapter 17. Information Expert • “… expresses the common ‘intuition’ that objects do things related to the information they have.” • Assign the responsibility for “knowing”
[something]
to the object (class) that has the information necessary to fulfill the responsibility. Creator • Assign to class B the responsibility to create an instance of class A if – B aggregates A objects. – B contains A objects. – B records instances of A objects. – B closely uses A objects. – B has the initializing data that will be passed to A when it is created. Farm Class Diagram Animal – name : String – kind : String + Animal ( [in] aKind : String , [in] aName : String ) + getKind ( ) : String Farm + Farm ( ) + add ( [in] animal : Animal ) : void + getNumberOfLegs ( ) : int * – animals Test Cases package farm.tests; … public class FarmTest extends …{ public void testGetNumLegs() { Farm f = new Farm(); f.add(new Animal(“Duck”, “Donald”)); assertEquals(2, f.getNumLegs()); f.add(new Animal(“Dog”, “Pluto”)); assertEquals(6, f.getNumLegs()); } } Animal Class public class Animal { private String name; private String kind; public Animal(String aKind, String aName) { kind = aKind; name = aName; } public String getKind() { return kind; } … Farm Class, public int getNumLegs() { int result = 0; Iterator it = animals.iterator(); while(it.hasNext()) { Animal a = (Animal) it.next(); if(a.getKind().equals(“Duck”)) { result += 2; } else if(a.getKind().equals( “Dog”)) { result += 4; } else { // ? } } return result; } Bad Smell in Farm.getNumLegs()? • Can you fix it? – Hints: • By Information Expert, who should know about the number of legs of Animals, the Farm or … ? • Having cascaded if’s (or switch statements) over information from another class is usually a very bad smell in OO. • Apply Larman’s GRASP principles of Information Expert and Polymorphism. GRASP: Polymorphism Principle Larman: • When related alternatives or behaviors vary by type (class), assign responsibility for the behavior—using polymorphic operations—to the types for which the behavior varies. Farm Example, Solution #1 Animal – name : String + Animal ( [in] aName : String ) + getName ( ) : String + getNumLegs ( ) : int Dog + Dog ( [in] aName : String ) + getNumLegs ( ) : int Duck + Duck ( [in] aName : String ) + getNumLegs ( ) : int Farm + Farm ( ) + add ( ) + getNumLegs ( ) – animals * { return 2; } abstract { return 4; } Farm Example, Solution #2 Animal – numberOfLegs : int – name : String + getName ( ) : String + getNumLegs ( ) : int # Animal ( [in] aName : String , [in] aNumberOfLegs : int ) Dog + Dog ( [in] aName : String ) Duck + Duck ( [in] aName : String ) Farm + Farm ( ) + add ( ) + getTotalNumLegs ( ) – animals * { return numberOfLegs; } General Classification of Kinds of Responsibility –Knowing – Doing Doing Doing responsibilities of an object include : – Doing something itself , such as creating an object or doing a calculation – Initialing action in other objects – Controlling and coordinating activities in other objects Knowing • Knowing responsibilities of object include : – Knowing about private encapsulated data – Knowing about related objects – Knowing about things it can derive or calculate Responsibilities and interaction diagrams • Interaction diagrams show choices in assigning responsibilities to objects. When these diagrams are created, decisions in responsibility assignment are reflected in the messages sent to different classes of objects. 2 RDD Example: Apply IE Information Expert: Give task to the object having the information to perform the task. Example: Larman 17.11 NextGEN POS application “Who should be responsible for knowing the grand total of a sale?” Fig. 9.2 NextGEN Domain Model Register Item Store address name Sale date time Payment amount Sales LineItem quantity Stocked-in * Houses 1..* Contained-in 1..* Records-sale-of 0..1 Paid-by 1 1 1 1 1 1 0..1 1 Captured-on concept or domain object association attributes Fig. 17.14 NextGEN Design Sale time Sales LineItem quantity Product Description description price itemID * Described-by Contains 1..* 1 1 IE Example Responsibilities • Sale: knows sale total • SalesLineItem: knows line item subtotal • ProductDescription: knows product price Fig. 17.17 NextGEN Design Sale time … getTotal() SalesLineItem quantity getSubtotal() Product Description description price itemID New method getPrice() :Product Description 1.1: p := getPrice() 1 *: st = getSubtotal : Sale t = getTotal lineItems[ i ] : SalesLineItem RDD Example: Apply Creator Larman 17.10: NextGEN example “Who should be responsible for creating a new SalesLineItem instance? • By Creator, we should look for a class that aggregates, contains, and so on, SalesLineItem instances. Consider the partial domain model in Figure 17.12. • Since a Sale contains (in fact, aggregates) many SalesLineItem objects, the Creator pattern suggests that Sale is a good candidate to have the responsibility of creating SalesLineItem instances. This leads to the design of object interactions shown in Figure 17.13. This assignment of responsibilities requires that a makeLineItem method be defined in Sale. Once again, the context in which we considered and decided on these responsibilities was while drawing an interaction diagram. Design Principles Design for change GRASP General Responsibility Assignment Software Patterns. • Information Expert • Creator • Low Coupling • High Cohesion • Controller (still to come, from ch17) • Polymorphism • … Cohesion • Measure of the degree of “relatedness” that elements within a module share. • Degree to which the tasks performed by a single module are functionally related. • Brain storm: – Why put procedures/methods together within a module/class? Levels Of Cohesion Coupling • Measures the degree of dependency that exists between modules. • Brain storm: – Give examples of code that creates coupling. Coupling A uses a service/method m of B A passes on an object o returned from B.m() A provides visibility of B to C by returning a reference to B in A.getB() A.m( B b, …) A calls C.m(B b …) which expects a B object A class X in A has an attribute of type Y defined in B Coupling A.m() changes an attribute in B via B.setX() A.m() changes a (public) attribute in B directly via assignment A changes a “flag” in B (ie an attribute which controls execution decisions in B; ie behaviour of B as seen by others) A and B both refer to an object o, and A can change o … How Do I Come Up With a Design? • Given – Product requirements. – Project plan • How do I come up with a design? Design – Repeat Successes • Has a (successful) similar product been built? • Yes, then reuse domain specific: – Architectural • Style (e.g. client/server, database, process control) • Patterns. – Design Patterns (& idioms). • Use Domain model as source of inspiration. Design – New Application Area? • Has a (successful) similar product been built? • No, then choose among general: – Architectural • Style (e.g. client/server, database, process control) • Patterns. – Design Patterns (& idioms). • Use Domain model as source of inspiration. Common Architectural Styles [FYI] • Dataflow – Pipes and filters – Batch sequential • Data-centered – Repository – Blackboard • Virtual Machine – Interpreter – Rule-based system • Call and Return – Main program and subroutine – Object-oriented (& Data abstraction) – Layered • Independent Components – Communicating processes – Client/server – Event systems • Implicit invocation • Explicit invocation Layered Architectural Style Our focus today: • Architectural style: Layered. • References – Larman, Chapter 13. – Fowler, EA. • Briefly, lets review Client-Server Client-Server (Two-tiered System) • “… most people see tier as implying a physical separation. Client-server systems are often described as two-tier systems …” [Fowler,p19] Enterprise Application Layers Calculate taxes Authorize payments Database Enterprise Application Layers Presentation Domain Logic Data Source Layering – General Scheme Layers • Presentation / Application. – UI. – Generally “thin”. • Domain / Business Logic. – Core system functionality. • Technical Services. Domain Logic (Layer) • “… also referred to as business logic. … It involves calculations based on inputs and stored data, validation of any data that comes in from the presentation, and figuring out exactly what data source logic to dispatch …” [Fowler, p.20] Layered Style Characteristics • Each layer offers services to layers above. • Hence, layers build upon each other to provide increased functionality. Layers: Functionality Presentation Domain Data Source Functionality / services Layers: Dependencies Presentation Domain Data Source Dependencies Layer Dependencies Example Log4J Technical Services Domain Presentation Persistence Jess POSRuleEngine Inventory ServiceAccess Payments Sales Pricing Swing Text SOAP Layering – Pure Style • Pure style: components are permitted to use services of other components in – same layer. – layer immediately below. Not permitted in pure style Where to Run Your Layers • [Folwer, pp. 22-24] Your software application Where to Run Your Layers EA software Technical Services EA Layers Refined Presentation Domain Logic Data Source General Layering Scheme Refined Presentation Domain Technical services • Presentation • Application • Domain (logic) • Low-level domain logic • Technical services • Foundation. General Layering Scheme Refined Presentation Domain Technical services • Presentation • Application • Business services • Low-level business services • Technical services • Low-level technical services Layering (Larman) Presentation (AKA Interface, UI, View) Application (AKA Workflow, Process, Mediation, App Controller) Domain(s) (AKA Business, Business Services, Model) Technical Services (AKA Technical Infrastructure, High-level Technical Services) Foundation (AKA Core Services, Base Services, Low-level Technical Services/Infrastructure) Business Infrastructure (AKA Low-level Business Services) GUI windows reports speech interface HTML, XML, XSLT, JSP, Javascript, … handles presentation layer requests workflow session state window/page transitions consolidation/transformation of disparate data for presentation handles application layer requests implementation of domain rules domain services (POS, Inventory) – services may be used by just one application, but there is also the possibility of multi-application services (relatively) high-level technical services and frameworks Persistence, Security low-level technical services, utilities, and frameworks data structures, threads, math, file, DB, and network I/O very general low-level business services used in many business domains CurrencyConverter •See Larman Sect 13.6 3 Encapsulation • A programming/design language mechanism. • A packaging / scoping mechanism for names – Names can refer to data, types, … – Especially, a means of packaging data. Data Access points at interface Information Hiding • Design principle by which a module is assigned a “secret”. • A module’s secret is usually – A design decision. • What type of design decisions might we want to hide from the clients of a module? Information Hiding • Often one hides, e.g. – Data representation. – Choice of algorithm. – Interface details / access mechanism of external entity (e.g. database, hardware) – … • Goal: particular design choice “invisible” to clients. • Why would we want to do this? Information Hiding • Information Hiding may or may not be supported at the programming language level. Servlets, The General Idea • Applet as a client side Java application. • Servlet as a server side technology for implementing part of the functionality of an application. • HTTP (URL) requests cause a servlet to be: – Instantiated (if it did not exist). – Run. – The servlet builds a response which is then sent back to the client (usually in the form of HTML). Servlet: HelloWeb public class HelloWebServlet extends HttpServlet { protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletOutputStream out = response.getOutputStream(); out.println(“Hello Web!”); } } Java Server Page • Servlet: – Embed HTML inside code. • JSP – Embed code inside HTML. HelloWeb.jsp <%@ page contentType=”text/html; charset=iso-8859-1″ language=”java” … %> Hello Web! Hello.jsp <%@ page contentType=”text/html; charset=iso-8859-1″ language=”java” … %> Hello <%= request.getParameter(“name”) %> Java Server Page • Implemented as a (special kind of) servlet. Model-View-Controller (MVC) Model Controller View Model-Views GRASP PATTERN: Controller • What object in the domain (or application coordination layer) receives requests for work from the UI layer? ??? Presentation Application Logic Video Store Record Rental Video ID … … … … … Clerk rent(videoID) Now what happens? PATTERN: Controller (Larman 17.13) • Problem: What object in the domain (or application coordination layer) receives requests for work from the UI layer? • System operations (see SSD): major input events to the system • The controller is the first object beyond the UI layer that is responsible for receiving or handling a system operations message. • Note that UI objects delegate system operation request to a controller. PATTERN: Controller (Larman 17.13) • Solution: Assign the responsibility to a class representing one of the following choices: • A façade controller, which represents – the overall system – A root object – A device that the software is running within, or – A major subsystem • A use case or session controller which represents a use case scenario in which the system operation occurs Fig. 17.21 Which class of object should be responsible for receiving this system event message? It is sometimes called the controller or coordinator. It does not normally do the work, but delegates it to other objects. The controller is a kind of “facade” onto the domain layer from the interface layer. actionPerformed( actionEvent ) : ??? : Cashier :SaleJFrame presses button enterItem(itemID, qty) UI Layer Domain Layer system operation message actionPerformed( actionEvent ) :Register : Cashier :SaleJFrame presses button 1: enterItem(itemID, qty) :Sale 1.1: makeLineItem(itemID, qty) Interface Layer Domain Layer system event message controller Fig. 17.24 Desirable coupling GRASP: Controller Illustration actionPerformed( actionEvent ) :Register : Cashier :SaleJFrame presses button 1: enterItem(itemID, qty) :Sale 1.1: makeLineItem(itemID, qty) Interface Layer Domain Layer system event message controller Presentation Application Fig. 17.22 Controller choices :Register enterItem(id, quantity) :ProcessSaleHandler enterItem(id, quantity) Fig. 17.26 Controller delegating work : Register : Sale addPayment( p ) p : Payment create() makePayment() Controller Illustration: Web-based EA Server :Tut06ControllerServlet HTTP Get doGet(req,resp) g:Greeting req: setAttribute(“Greeting”,g) forward(“…/Greeting.jsp”) Greeting.jsp getAttribute(…) g … getGreeting() Web-based Enterprise Applications • The big picture … Enterprise Applications: Layers Domain Data Source Presentation Domain Data Source Table Data Gateway Transaction Script Domain Model Row Data Gateway Data Mapper Front Controller Template View Transform View Page Controller Presentation Active Record List of Main Patterns To Be Studied Domain Data Source Table Data Gateway Transaction Script Domain Model Row Data Gateway Data Mapper Active Record Front Controller Template View Transform View Page Controller Presentation EA: MVC Domain Data Source Domain Model Page Controller Template View Presentation EA: MVC Example: Greeting Greeting Template View (Greeting.jsp) Page Controller (Greeting servlet) Domain Data Source Table Data Gateway Transaction Script Domain Model Row Data Gateway Data Mapper Front Controller Template View Transform View Page Controller Presentation Active Record Enterprise Application Patterns Domain Data Source Table Data Gateway Transaction Script Domain Model Row Data Gateway Data Mapper Active Record Front Controller Template View Transform View Page Controller Presentation Data Source Patterns Data Source Patterns • Hide SQL. • Provide an abstraction for – One data row. – A collection of data row(s). Example: Person-Grade Table Table attributes: • name : String • grade : int name grade Table Data Gateway PersGradeTDG – PersGradeTDG() + find(name) : ResultSet + findInRange(fg,tg) : ResultSet + insert(name,grade) : void + update(name,grade) : void + delete(name) : void Table Data Gateway: Find Code Table Data Gateway: FindInRange Active Record (Row Data Gateway) PersGradeAR name : String grade : int PersGradeAR(name, g) find(name) … // like RDG // Can also have domain logic getRank() 4 Domain Data Source Table Data Gateway Transaction Script Domain Model Row Data Gateway Data Mapper Front Controller Template View Transform View Page Controller Presentation Active Record Enterprise Application Patterns Domain Data Source Table Data Gateway Transaction Script Domain Model Row Data Gateway Data Mapper Active Record Front Controller Template View Transform View Page Controller Presentation Data Source Patterns 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’ • Our PersGradeRDG (next slide) combines Row Data Gateway PersGradeRDG – name : String – grade : int + PersGradeRDG(name, grade) + find(name) : PersGradeRDG + insert() : void + update() : void + delete() : void + … getters and setters … Row Data Gateway: Find Code Row Data Gateway • Code sample for Fowler’s PersonRDG • Note ‘find’ method is static – it is class method GetByLastName Example Simple web application to Input a student’s last name Fetch database record Output student’s full name GetByLastName Will look at Row Data Gateway PageController Transaction Script Row Data Gateway • StudInfoRDG – Represents record in DB of student • StudInfoFinder – Finds student record based on lastName – Returns the StudInfoRDG – Locates DB using DBRegistry Domain Data Source Table Data Gateway Transaction Script Domain Model Row Data Gateway Data Mapper Front Controller Template View Transform View Page Controller Presentation Active Record Enterprise Application Patterns Transaction Script Fowler: A TS organizes the business logic primarily as a single procedure where each procedure handles a single request from the presentation. The TS may make calls directly to the DB or through a thin DB wrapper. Think of a script for: a use case or business transaction. Implementation can be – shared among subroutines. – Subroutines can be used by more than one script Transaction Script • … is essentially a procedure that takes the – input from the presentation, – processes it with validations and calculations, – stores data in the database, – (invokes any operations from other systems, and) – replies with more data to the presentation perhaps doing more calculation to help organize and format the reply data. (Fowler) GetByLastName Will look at Row Data Gateway PageController Transaction Script Do-it-all Transaction Script A TS that does all the work itself Without a Finder Without a RDG Directly calls DB Do-it-all Servlet or Script, Class public class DoItAll extends javax.servlet.http.HttpServlet { protected void doGet( HttpServletRequest request, HttpServletResponse response) throws … // { … } } Do-it-all Transaction Script, doGet() String lastName = request.getParameter(“…”); Connection dbc = DbRegistry.getDbConnection(); String findSql = “SELECT * from … where LastName = ?”; PreparedStatement dbQuery = dbc.prepareStatement(findSql); dbQuery.setString(1, lastName); ResultSet rs = dbQuery.executeQuery(); rs.next(); String firstName = rs.getString(“FirstName”); lastName = lastName.toUpperCase(); PrintWriter out = response.getWriter(); response.setContentType(“text/html”); out.println(“
Hello “+firstName+” “+lastName+”
“); Outline • Controller patterns – Focus: Page Controller Domain Data Source Table Data Gateway Transaction Script Domain Model Row Data Gateway Data Mapper Active Record Front Controller Template View Transform View Page Controller Presentation Controller Patterns Page Controller Fowler: A Page Controller is an object that handles a request for a specific page or action on a web site. There is one input controller for each logical page of the web site. Page Controller handles the http get and post Decides which model and view to use Page Controller Responsibilities: – Decode the URL, extract any form data, decide action – Create and invoke any model objects • All relevant data from the html request should be passed to the model, so the model does not need any connection to html request – Determine which view should display the result page • Forward model information to it Helper objects can be created/used to perform tasks that are shared Page Controller Fowler Example: display info about a recording artist – ActionServlet implements common ‘forward’ task – ArtistController implements doGet() • Checks artist name is ok • Creates a new ArtistHelper object with Artist as attribute • Adds helper information to html request • Forwards request to Artist.jsp – Artist.jsp is a TemplateView which gets information to display from helper object (which it gets from request) Page Controller GetByLastName Will look at Row Data Gateway PageController Transaction Script Page Controller SOEN EA sample: display info about a student – PageController implements doGet() • Delegates to transaction script Note: does not follow Fowler’s use of .jsp delegates rather than forwards no explicit helper object (really StudInfoRDG is helper) 5 Architecture • … deals with the top-level structure. – Components – Interrelationships Documentation of Architectures • Architecture Document = View A + View B + View C + … View X + “Beyond Views” “4+1” View Model of Arch. • By Philippe Kruchten [Kruchten95] • Rational Unified Process. “4+1” View Model of Arch. Deployment/ Implementation/ “4+1” View Model of Arch. Deployment/ Implementation/ • Logical View – The object model of the system • Process View – The behavioural model of the system • Implementation View – The software components, libraries, packages, etc • Deployment View – How software maps to hardware “4+1” View Model of Arch. Deployment/ Implementation/ • Use Case View – The scenarios of the system – Ties everything together • Allows tracing of other views for verification – Note that scenarios can cover non-functional requirements too Logical View Fig. 39.1 Log4J Technical Services Domain UI Pricing Persistence DBFacade Taxes 玦nterface? ITaxCalculatorAdapter Services Factory Sales Register Sale Swing ProcessSale Frame Payments CreditPayment 玦nterface? ICreditAuthorization ServiceAdapter ServiceAccess Inventory 玦nterface? IInventoryAdapter Jess POSRuleEngine POSRuleEngineFacade SOAP Deployment View Fig. 39.2 玹erminal? : POSTerminal { JVM = Sun Hotspot Client 2.0 } custom protocols on top of TCP 玜rtifact? NextGenClient.jar 玸erver? : Dell PowerEdge 3600 { OS=Red Hat Enterprise Linux 4 } 玠atabase? : PostgreSQL 10 玜rtifact? Product Tables 玸erver? : Dell PowerEdge 3600 { OS=Red Hat Enterprise Linux 4 } 玜rtifact? GoodAsGoldTaxCalculator.exe 玸erver? : GenericServer 獷 RP? : SAP 玸erver? : GenericServer 玸ystem? CreditPayment Authorizer SOAP over HTTP VISA protocol over TCP SQL over TCP inventory and accounting GRASP • Information Expert. • Creator. • High Cohesion. • Low Coupling. • Controller. • Polymorphism. • Pure Fabrication. • Indirection. • Protected Variations. GRASP: Polymorphism Principle (done) Larman: • When related alternatives or behaviors vary be type (class), assign responsibility for the behavior—using polymorphic operations—to the types for which the behavior varies. GRASP Protected Variations • Problem: How to design objects, subsystems, and systems so that the variations or instability in these elements does not have an undesireable impact on other elements? • Solution: Identify points of predicted variation or instability; assign responsibility to create a stable interface around them. Core PV Mechanisms • Encapsulation. • Interfaces. • Polymorphism. • Indirection, … (Note: we are speaking of mechanisms, not principles) PV: Pick Your Battles • Beware not to try to overly “future-proof” your designs. • Actually, this is true of any principle … Applying PV to Web EA • Consider a single servlet which offers the greeting “Hello”. • Refactor it with the goal of applying PV and separate concerns. #doGet(in req, in resp) GreetingServlet Applying PV to Web EA • Greeting example with successively refined design solutions: 1. Start from design of 1 servlet class whose purpose is to offer a greeting. 2. Factor out domain logic to create design with: • Servlet in Application layer. • A class in Domain Logic layer to be responsible for domain logic. • How are the responsibilities of MVC distributed now? 3. Separate V and C by using JSP for V. Domain Data Source Transaction Script Domain Model Data Mapper Row Data Gateway Front Controller Template View Transform View Page Controller Presentation Active Record EA Patterns Table Module Table Data Gateway Domain Data Source Transaction Script Active Record Front Controller Page Controller Template View Presentation Domain Logic Patterns Domain Model Data Mapper Transform View Table Data Gateway Table Module Row Data Gateway Domain Logic (Layer) • “… also referred to as business logic. … It involves calculations based on inputs and stored data, validation of any data that comes in from the presentation, and figuring out exactly what data source logic to dispatch …” p.20 Organizing the Domain Logic • Key architectural decisions, which influence structure of other layers. • Pure, hybrid patterns. Pure Domain Logic Patterns • Two main alternatives: – Transaction Script – Domain Model Hybrid Domain Logic • Hybrid (Domain & Data Source) alternatives: – Active Record – Table Module • To be discussed a little later. • For now, focus on the pure Domain Logic patterns. Choosing a Domain Logic Pattern • Which one to choose? – Influenced by the complexity of domain logic. Choosing Between TS & DM • Application is simple access to data sources Transaction Script, (or Active Record, Table Module) • Significant amount of business logic Domain Model • TS is simpler: – Easier and quicker to develop and maintain. – But can lead to duplication in logic / code. TS DM, Easy of Refactoring? • Easier to refactor TS DM than DM TS. Transaction Script (done) Domain Model (EA Pattern) Fowler: An object model of the domain that incorporates both behaviour and data. A DM creates a web of interconnected objects, where each object represents some meaningful individual, whether as large as a corporation or as small as a single line in an order form. Domain Model (EA Pattern) • Realization (via design classes) of UML Domain Model (conceptual classes). – E.g. person, book, shopping cart, task, sales line item, … • Domain Model classes contain – Logic for handling validations and calculations. • E.g. a shipment object – calculate the shipping charge for a delivery. • Can still have routines for actions (e.g. checkout) – but they quickly delegate to method in Domain Model. [Example] Revenue Recognition (RR) • Revenue recognition is a common problem in business systems. – when you can actually count the money you receive on your books. • E.g. selling a S/W package $120 today – Book $40 today, – $40 in 30 days, – $40 in 60 days. • (Taken from Fowler’s PEAA) [E.g.] RR for SimpleSoft • Company named SimpleSoft • Sells S/W: – Word processor, – Database, – Spreadsheet. • Contract: covers only one product. • Revenue recognition varies per product. [E.g.] RR for SS: Conceptual Model [E.g.] TS: Calculating Revenue Recognitions [E.g.] Domain Model: Calculating Revenue Recognitions [E.g.] Enhancement: e.g. New Revenue Recognition Strategy • Transaction Script: – New conditional, or – New subroutine. • Domain Model: – Create new Rev. Recog. Strategy class. Domain Data Source Transaction Script Active Record Front Controller Page Controller Template View Presentation Data Source Patterns Domain Model Data Mapper Transform View Table Data Gateway Table Module Row Data Gateway Data Source Patterns • Pure patterns. • Hybrid patterns. Pure Data Source Patterns • Gateways (previously covered) – Row Data Gateway (RDG) – Table Data Gateway (TDG) • Data Mapper – To be explained in a few slides. Row Data Gateway (done) • 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’ • Our PersGradeRDG combines Row Data Gateway (done) • StudInfoRDG – Represents record in DB of student • StudInfoFinder – Finds student record based on lastName – Returns the StudInfoRDG – Locates DB using DBRegistry 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. Table Data Gateway PersGradeTDG – PersGradeTDG() + find(name) : ResultSet + findInRange(fg,tg) : ResultSet + insert(name,grade) : void + update(name,grade) : void + delete(name) : void Hybrid Data Source Patterns • Active Record = RDG + Domain Logic. • Table Module ≈ TDG + Domain Logic. – TDG like module that processes ResultSets. Active Record Fowler: An object that wraps a row in a database table or view, encapsulates the database access, and holds domain logic on that data. An AR object carries both data and behaviour. The essence of an AR is a Domain Model in which the classes match very closely the record structure of the underlying database. Active Record (Row Data Gateway) PersGradeAR name : String grade : int PersGradeAR(name, g) find(name) … // like RDG // Can also have domain logic getRank() Table Module • Similar to Active Record • Table Module = TDG plus domain logic 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 • E.g. … Data Mapper Example (Tasks) «Domain Model» Task – id : long – isDone : boolean – title : String + Task ( ) + Task ( [in] aTitle : String ) + getId ( ) : long + getTitle ( ) : String + isDone ( ) : boolean + setId ( [in] anId : long ) : void + setIsDone ( [in] b : boolean ) : void TaskMapper – TaskMapper ( ) + find ( [in] id : long ) : Task + findAll ( ) : List + insert ( [in] task : Task ) : void + update ( [in] task : Task ) : void + delete ( [in] task : Task ) : void DBMS 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. • E.g. … Domain Data Source Table Data Gateway Transaction Script Domain Model Data Mapper Row Data Gateway Front Controller Template View Transform View Page Controller Presentation Active Record Enterprise Application Patterns (v1.3) Table Module Recall the Greeting EA • A single servlet which offers the greeting “Hello”. • We refactored it, offering two alternative designs. #doGet(in req, in resp) GreetingServlet Review Question • On a blank sheet of paper … • Provide three class diagrams corresponding to the three design solutions of the Greeting EA. Evaluating a Design • Which is a better design? • What is a good design? What is a good design? • Satisfies user needs, requirements. • Reveals intent. • Is as simple as possible. • Minimizes cost of … likely changes. And … • High cohesion. • Low coupling. Greeting EA Evolution … What if … • Support a personalized greeting. • Change “look” of output (e.g. bold the name). • Get full name from db. Comparing Design Solutions Property Sol’n 1 Sol’n 2 Sol’n 3 Correct Intent clear Simplest Acc. Change Cohesion Coupling 6 Front Controller Fowler: A controller that handles all requests for a web site. The Front Controller consolidates all request handling by channeling requests through a single handler object. This object can carry out common behaviour which can be modified at runtime with decorators. This handler then dispatches to command objects for behaviour particular to a request. Front Controller GoF design pattern: Command Use a Command object to encapsulate the steps that are executed by a command. Command::doIt() executes command Allows Command::unDoIt() etc GoF design pattern: Decorator Decorator::m() adds additional behaviour, but delegates to real Object::m() for real behaviour Eg, logging command execution before/after executing command Page vs Front Controller – Differences in URL Page Controllers for A1 • http:/stu.cs/343A1/ViewTaskList • http:/stu.cs/343A1/AddTask • http:/stu.cs/343A1/RemoveAllTasks • … Front Controller for A1 • Base URL: http:/stu.cs/343A1/frontController • …/frontController ?command=ViewTaskList • …/frontController ?command=AddTaskGrade&title=abc&… Front Controller FrontServlet # processRequest ( ) – getCommand ( ) – getCommandClass ( ) FrontCommand + init ( ) + processRequest ( ) AddStudent + processRequest ( ) Servlet + init ( ) + destroy ( ) # processRequest ( ) # doGet ( ) # doPost ( ) + getServletInfo ( ) + forward ( ) + forwardAbsolute ( ) + getUrlBase ( ) # controller 0..1 Error + processRequest ( ) Front Controller Front Controller (Fowler) Command (GoF) Patterns FrontCommand + init ( ) + processRequest ( ) ViewStudInfoCommand + processRequest ( ) RemoveStudentCommand + processRequest ( ) FrontControllerServlet # processRequest ( ) – getCommand ( ) – getCommandClass ( ) + getUrlBase ( ) Front Controller: Sequence Diagram Front Controller: ProcessRequest Front Controller (cont’d) Front Controller: Advantages? Web EA Redesign Exercise • Refactoring a DoItAll Servlet, let me count the ways … Domain Data Source Do -it -all Servlet or Script Presentation Do -it -all Servlet or Script Do-it-all Servlet or Script, Class public class DoItAll extends javax.servlet.http.HttpServlet { protected void doGet( HttpServletRequest request, HttpServletResponse response) throws … // { … } } Redesigning This Application • Redesign DoItAll so as to increase the class cohesion. • Create new classes. Which EA patterns would you use? • Distribute the doGet() method code (given on the next slide) into the new classes. Identify which lines would go into which classes. Do-it-all Transaction Script, doGet() String lastName = request.getParameter(“…”); Connection dbc = DbRegistry.getDbConnection(); String findSql = “SELECT * from … where LastName = ?”; PreparedStatement dbQuery = dbc.prepareStatement(findSql); dbQuery.setString(1, lastName); ResultSet rs = dbQuery.executeQuery(); rs.next(); String firstName = rs.getString(“FirstName”); lastName = lastName.toUpperCase(); PrintWriter out = response.getWriter(); response.setContentType(“text/html”); out.println(“
Hello “+firstName+” “+lastName+”
“); Do-it-all Servlet Redesign: Separating Concerns • The next few slides show ways in which we can separate concerns; i.e. distribute the functionality of the do-it-all script into separate classes. • Combinations other than the ones shown are possible. Domain Data Source Do -it -all Presentation Redesigning Do -it -all (2 classes) [#1] redesign Note: Domain Data Source Do -it -all Presentation Redesigning Do -it -all (3 classes) [#3] redesign Domain Data Source Do -it -all Presentation Redesigning Do -it -all (4 classes) [#4] redesign Domain Data Source Do -it -all Presentation Redesigning Do -it -all : Adding … (5 classes) [#5] redesign Domain Data Source Do-it-all Presentation Redesigning Do-it-all : Adding … [#5b] redesign Domain Data Source Do-it-all Presentation Redesigning Do-it-all (5 classes) [#5c] redesign • Is there anything wrong with this design? (Hint: consider the dependencies and the layering style.) Domain Data Source Do-it-all Presentation Redesigning Do-it-all (6 classes) [#6] redesign Pure Fabrication Problem: Existing objects, ie domain objects, are not appropriate to have the responsibility Solution suggested by Information Expert not appropriate Might violate high cohesion, low coupling Solution: Fabricate (ie create, make up) a new object to hold the responsibility GRASP: Pure Fabrication • Assign a highly cohesive set of responsibilities to an artificial or convenience class that does not represent a problem domain concept—something made up, to support high cohesion, low coupling, and reuse. • Can you think of an example from EA? GRASP: Pure Fabrication Design of objects – Representational decomposition – Behavorial decomposition It’s OK for OO software to have objects representing behaviour, ie use case, process, function, strategy, TS But do not overdo it All GoF design patterns are Pure Fabrications Indirection Problem: How to assign responsibility to avoid direct coupling? How to de-couple objects? Solution: Assign responsibility to an intermediatory object to mediate between the two components Example: Adapter pattern Intermediatory to external tax calculators Fig. 25.10 : Sale :TaxMasterAdapter taxes = getTaxes( s ) t = getTotal the adapter acts as a level of indirection to external systems TCP socket communication xxx … 玜ctor? . . . :TaxMasterSystem Indirection “Most problems in computer science can be solved by another level of indirection” 7 Indirection Problem: How to assign responsibility to avoid direct coupling? How to de-couple objects? Solution: Assign responsibility to an intermediatory object to mediate between the two components Example: Adapter pattern Intermediatory to external tax calculators Fig. 25.10 : Sale :TaxMasterAdapter taxes = getTaxes( s ) t = getTotal the adapter acts as a level of indirection to external systems TCP socket communication xxx … 玜ctor? . . . :TaxMasterSystem Indirection “Most problems in computer science can be solved by another level of indirection” Patterns and Principles We have (and still are) studying: • Larman’s GRASP • GoF • Fowler’s EA The most fundamental are the principles. GRASP: Interrelationships Protected Variation Mechanism Low Coupling Mechanism Indirection Mechanism Adapter Pure Fabrication Polymorphism Example GoF Design Patterns GRASP Principles High Cohesion Mechanism Patterns apply principles, Pro e.g. … tected Variation Mechanism Low Coupling Mechanism Indirection Mechanism Adapter Pure Fabrication Polymorphism Example GoF Design Patterns GRASP Principles High Cohesion Mechanism Gang Of Four • Gamma, Helm, Johnson, Vlissides • Some patterns in Larman, Chap. 23,… • All patterns in XDE – As documentation. – As dynamic templates. •Present solutions to common software problems arising within a certain context Overview of Patterns •Capture recurring structures & dynamics among software participants to facilitate reuse of successful designs The Proxy Pattern 1 1 Proxy service Service service AbstractService service Client •Help resolve key software design forces •Flexibility •Extensibility •Dependability •Predictability •Scalability •Efficiency •Generally codify expert knowledge of design strategies, constraints & “best practices” GoF Pattern Summary & Relationships GoF Pattern Classification • Behavioral Patterns • Creational Patterns • Structural Patterns GoF Behavioral Patterns • Chain of Responsibility • Command • Interpreter • Iterator • Mediator • Memento • Observer • State • Strategy • Template Method • Visitor GoF Creational Patterns • Abstract Factory • Builder • Factory Method • Prototype • Singleton Command Pattern (Week 1 and Front Controller) Problem: How to allow the same command to be invoked by – Menu selection – Alt-ctrl shortcut – Commandline text entry, etc • How to allow (unlimited) undo/redo • How to keep a log/audit/history of commands invoked • How to allow “macro” commands to be defined Command Pattern (Week 1 and Front Controller) • You have commands that need to be – executed, – undone, or – queued • Command design pattern separates – Receiver from Invoker from Commands • All commands derive from Command and implement do(), undo(), and redo() • Also allows recording history, replay Design Issue: Ensure No More Than One Instance of a Class is Created • Given a class C, how can we ensure that only one instance of C is ever created? C – attribute1 – attribute2_etc + C ( ) + methodA ( ) + methodB_etc ( ) Converting C to a Singleton. C – attribute1 – attribute2_etc + C ( ) + methodA ( ) + methodB_etc ( ) «Singleton» C – attribute1 – attribute2_etc – uniqueInstance : C – C ( ) + getUniqueInstance ( ) + methodA ( ) + methodB_etc ( ) Singleton Pattern Notice: • Constructor is no longer public. • To access the instance use getUniqueInstance(). • All other attribute and method declarations of C stay the same. «Singleton» C – attribute1 – attribute2_etc – uniqueInstance : C – C ( ) + getUniqueInstance ( ) + methodA ( ) + methodB_etc ( ) «Singleton» C.getUniqueInstance() public static C getUniqueInstance() { if(uniqueInstance == null) { uniqueInstance = new C(); } return uniqueInstance; } Thread-safe Creation Method public static synchronized C getUn…() { … } Singleton: Design Alternatives/Issues • Create a class with static attributes and methods. Trade-offs: consider how easy the following are: • Adapting the design so that x instances can be created (where x > 1). • Subclassing. • Passing the instance as a parameter. • … • (See Larman05, Section 26.5) Singleton: Design Issues (Cont’d) • See Larman05, Section 26.5 for discussion of – Design trade-offs, including • eager/lazy evaluation of Singleton.uniqueInstance see. Singleton & UML 1 ServicesFactory instance : ServicesFactory accountingAdapter : IAccountingAdapter inventoryAdapter : IInventoryAdapter taxCalculatorAdapter : ITaxCalculatorAdapter getInstance() : ServicesFactory getAccountingAdapter() : IAccountingAdapter getInventoryAdapter() : IInventoryAdapter getTaxCalculatorAdapter() : ITaxCalculatorAdapter … // static method public static synchronized ServicesFactory getInstance() { if ( instance == null ) instance = new ServicesFactory() return instance } UML notation: this ‘1’ can optionally be used to indicate that only one instance will be created (a singleton) Singleton & UML :Register 1 :ServicesFactory aa = getAccountingAdapter initialize … the ‘1’ indicates that visibility to this instance was achieved via the Singleton pattern Dice Game Simple game: Player rolls a dice Score is the face value of the dice Client Cannot Tell … +roll() +getFaceValue() : int «interface» IDice DiceGame * Dice Game Refactoring We can apply: • Indirection principle. – Decouple DiceGame from Dice by inserting an IDice interface in between. • Introduce a Simple Factory class, DiceFactory. • Make DiceFactory a Singleton. Dice Game: New Functionality Although we have ConstDice we still have a Problem: • Our DiceFactory only creates one type of IDice. Solutions: • Somehow we want the behavior of createDice() to vary. DiceFactory.createDice(). • Possible solutions: – DiceFactory can read a System property to determine the class to instantiate (Larman05, p.441). – Add a method to factory: – Generalize our solution further: Abstract Factory. • Any of these solutions will finally allow us to create our test class, … e.g. DiceGameTest JUnit TestCase public void testWinning() { int faceValue = 3; DiceFactory.theOne(). DiceGame game = new DiceGame(); game.roll(); assertEquals(“face value”, faceValue, game.getFaceValue()); assertTrue(“won”, game.won()); } Factory • Context / problem: Who should be responsible for creating objects when there are special considerations, such as complex creation logic, a desire to separate the creation responsibilities for better cohesion, and so forth? • Solution: Create a Pure Fabrication object called a Factory. Factory Example ServicesFactory accountingAdapter : IAccountingAdapter inventoryAdapter : IInventoryAdapter taxCalculatorAdapter : ITaxCalculatorAdapter getAccountingAdapter() : IAccountingAdapter getInventoryAdapter() : IInventoryAdapter getTaxCalculatorAdapter() : ITaxCalculatorAdapter … { if ( taxCalculatorAdapter == null ) { // a reflective or data-driven approach to finding the right class: read it from an // external property String className = System.getProperty( “taxcalculator.class.name” ); taxCalculatorAdapter = (ITaxCalculatorAdapter) Class.forName( className ).newInstance(); } return taxCalculatorAdapter; } Larman’s comment on prev. figure • Note that the factory methods return objects types to an interfacre rather than a class so that the factory can return any implementation of the interface. • Factory methods can also (Abstract) Factory Example (GoF) Factory (in EAs) FrontCommand + init ( ) + processRequest ( ) ViewStudInfoCommand + processRequest ( ) RemoveStudentCommand + processRequest ( ) FrontControllerServlet # processRequest ( ) – getCommand ( ) : FrontCommand – getCommandClass ( ) New Version of Dice Game • Support using a pair of Dice. • How can this be added? Multi-Dice Design Composite (Larman05, 26.8) Context/problem • How do you treat a group or composite structure of objects the same way (polymorphically) as a non-composite (atomic) object? Solution • Define classes for composite and atomic objects so that they implement the same interface. Dice Composite +roll() +getFaceValue() : int «interface» IDice +roll() +getFaceValue() : int +Dice() Dice +roll() +getFaceValue() : int +ConstDice(in faceValue : int) -faceValue : int ConstDice +roll() +getFaceValue() : int +DicePair(in d1 : IDice, in d2 : IDice) DicePair -dice 2 for(IDice d : dice) d.roll(); sum = 0; for(IDice d : dice) sum += d.getFaceValue(); Client Cannot Tell … +roll() +getFaceValue() : int «interface» IDice DiceGame * Composite: Ex. Objects Composite: Ex. Class Diagram Must “add” be implemented by Line? • In C++ add declared virtual; subclass need not implement it. • In Java if add is abstract, then subclasses must implement it. String add(Graphic g) { throw new UnsupportedOperationException(); } • Can you think of a better solution? Composite: Clients point-of-view «interface» ISalePricingStrategy getTotal( Sale ) : Money 1..* pricingStrategies Sale date … getTotal() … * 1 { … return pricingStrategy.getTotal( this ) } PercentageDiscount PricingStrategy percentage : float getTotal( Sale ) : Money AbsoluteDiscount OverThreshold PricingStrategy discount : Money threshold : Money getTotal( Sale ) : Money «interface» ISalePricingStrategy getTotal( Sale ) : Money Composite PricingStrategy add( ISalePricingStrategy ) getTotal( Sale ) : Money 1..* pricingStrategies Composite Pricing Strategies • Interface • Realization GoF Structural Patterns • Adapter • Bridge • Composite • Decorator • Facade • Flyweight • Proxy Adapter • Context / problem How to resolve incompatible interfaces, or provide a stable interface to similar components with different interfaces? • Solution: Convert the original interface of a component into another interface, through an intermediate adapter object. Adapter • Suppose we have a tax calculation class (or external library) but the interface is not well suited for our application. +computeTax() : double GoodAsGoldTaxPro Adapter • Adapter provides an interface suited to the application GoodAsGoldTaxProAdapter getTaxes( Sale ) : List of TaxLineItems computeTax(…):double GoodAsGoldTaxPro Adapter (For More than One Class) • What if more than one class (library) needs to be adapted? Adapter TaxMasterAdapter getTaxes( Sale ) : List of TaxLineItems GoodAsGoldTaxPro Adapter getTaxes( Sale ) : List of TaxLineItems «interface» ITaxCalculatorAdapter getTaxes( Sale ) : List of TaxLineItems +computeTax() : double GoodAsGoldTaxPro * * 8 GoF Structural Patterns • Adapter • Bridge • Composite • Decorator • Facade • Flyweight • Proxy Adapter • Context / problem How to resolve incompatible interfaces, or provide a stable interface to similar components with different interfaces? • Solution: Convert the original interface of a component into another interface, through an intermediate adapter object. Adapter • Suppose we have a tax calculation class (or external library) but the interface is not well suited for our application. +computeTax() : double GoodAsGoldTaxPro Adapter • Adapter provides an interface suited to the application GoodAsGoldTaxProAdapter getTaxes( Sale ) : List of TaxLineItems computeTax(…):double GoodAsGoldTaxPro Adapter (For More than One Class) • What if more than one class (library) needs to be adapted? Adapter TaxMasterAdapter getTaxes( Sale ) : List of TaxLineItems GoodAsGoldTaxPro Adapter getTaxes( Sale ) : List of TaxLineItems «interface» ITaxCalculatorAdapter getTaxes( Sale ) : List of TaxLineItems +computeTax() : double GoodAsGoldTaxPro * * Facade Facade Strategy • Context / problem: How to design for varying, but related, algorithms or policies? How to design for the ability to change (even dynamically) these algorithms or policies? • Solution: Define each algorithm/policy/strategy in a separate class with a common interface Strategy PercentDiscount PricingStrategy percentage : float getTotal( s:Sale ) : Money AbsoluteDiscount OverThreshold PricingStrategy discount : Money threshold : Money getTotal( s:Sale ) : Money «interface» ISalePricingStrategy getTotal( Sale ) : Money { return s.getPreDiscountTotal() * percentage } { pdt := s.getPreDiscountTotal() if ( pdt < threshold ) return pdt else return pdt – discount } How Do We Create a Strategy? 1 PricingStrategyFactory instance : PricingStrategyFactory getInstance() : PricingStrategyFactory getSalePricingStrategy() : ISalePricingStrategy getSeniorPricingStrategy() : ISalePricingStrategy … { String className = System.getProperty( “salepricingstrategy.class.name” ); strategy = (ISalePricingStrategy) Class.forName( className ).newInstance(); return strategy; } Observer Pattern Goal: When the total of the sale changes, refresh the display with the new value Sale total … setTotal( newTotal ) … Observer • How shall we have the display be updated? • Why not … have the Sale inform the display when it changes value. What is Wrong With This? Sale total … setTotal( newTotal ) … update( ) Observer Pattern • Context / Problem: Different kinds of subscriber objects are interested in the state changes or events of a publisher object, and want to react in their own way when the publisher generates the event. … Observer Pattern • Solution: Define a “subscriber” or “listener” interface. Subscribers implement this interface. The publisher can dynamically register subscribers who are interested in an event, and notify them when an event occurs. • Clarification: Publisher can dynamically process registration requests from subscribers. Observer Pattern (GoF book) Observers: Illustration Sale Example «interface» PropertyListener onPropertyEvent( source, name, value ) SaleFrame1 onPropertyEvent( source, name, value ) initialize( Sale sale ) … javax.swing.JFrame … setTitle() setVisible() … Sale addPropertyListener( PropertyListener lis ) publishPropertyEvent( name, value ) setTotal( Money newTotal ) … * propertyListeners Recall … • Way back in week 5 we asked the question … How do I come up with a design? How Do I Come Up With a Design? • What are the inputs to the activities of design? • What are the outputs? Design Activities: Inputs & Outputs • Product requirements • Project plan • Architectural factors … • ArchitectureDocument – Architectural Style(s) • … Design Input: SRS • What is contained in the SRS? (name some of its parts) • Domain Model • Use Case Model • Design Model • Control Style / Pattern • User-interface design … Design: From SRS to … Design Model Classes • Domain Model often used as first approximation to Design Model. • Domain Model contains – Conceptual classes • Conceptual classes used as basis for similarly named design classes. • (E.g. Larman, Chapter 16, p. 222.) Domain Data Source Transaction Script Data Mapper Row Data Gateway Front Controller Template View Transform View Page Controller Presentation Active Record EA Patterns Table Module Table Data Gateway Domain Model Enterprise Applications:Domain Model • Requirements Domain Model • Design Model: classes Domain Model pattern From Requirements to Design Requirements artifacts: e.g. • Domain Model • Use Case Model Design artifacts: e.g. • Software Architecture Document • Design Model • User-interface design … Payment amount Sale date time Pays-for Payment amount: Money getBalance(): Money Sale date: Date startTime: Time getTotal(): Money . . . 1 1 Conceptual Classes to Design Classes • Domain Model pattern Representational Gap • Larman, Section 17.2: The object developer has taken inspiration from the real-world domain in creating software classes. Therefore, the representational gap between how stakeholders conceive the domain, and its representation in software, has been lowered. Register Item Store address name Sale date time Payment amount Sales LineItem quantity Customer Cashier Manager Product Catalog Product Specification description price itemID Stocks * Houses 1..* Used-by * Contains 1..* Describes * Captured-on Contained-in 1..* Described-by * Records-sale-of 0..1 Started-by Paid-by Initiated-by Logs- completed * Records-sales-on 1 1 1 1 1 1..* 1 1 1 1 1 1 1 1 1 1 1 1 From Rich Conceptual Domain Model to Rich set of Domain Model classes SalesLineItem quantity : Integer getSubtotal() ProductCatalog … getSpecification(…) ProductSpecification description : Text price : Money itemID : ItemID … Store address : Address name : Text addSale(…) Payment amount : Money … Contains 1..* Contains 1..* Register endSale() enterItem(…) makeNewSale() makePayment(…) Sale date : Date isComplete : Boolean time : Time becomeComplete() makeLineItem(…) makePayment(…) getTotal() Captures Houses Uses Looks-in Paid-by Describes 1 1 1 1 1 1 1 1 1 1 1 1 1 * Logs-completed * 1