Software Arch & Design
Software Arch & Design CS 6310
Popular in Course
Popular in ComputerScienence
This 0 page Class Notes was uploaded by Alayna Veum on Monday November 2, 2015. The Class Notes belongs to CS 6310 at Georgia Institute of Technology - Main Campus taught by Staff in Fall. Since its upload, it has received 43 views. For similar materials see /class/234135/cs-6310-georgia-institute-of-technology-main-campus in ComputerScienence at Georgia Institute of Technology - Main Campus.
Reviews for Software Arch & Design
Report this Material
What is Karma?
Karma is the currency of StudySoup.
Date Created: 11/02/15
JAVA DESIGN GOALS Simplicity Security Familiarity Portability 3 No preprocessor NO includes NO olefines No conditional compilation No explicit pointers or references No multiple inheritance NO unsigned No operator overloading 3 No goto statement No free statement NO typedefs No structures No enumerations No unions No functions No templates No shadowing of parameters No machinedependent primitive SlzeS int short long etc ADDITIONS TO C Threads Booleans Iterators 1stclass arrays Interfaces Garbage collection 0Bytes Class Object Unicode Reflection ADDITIONS TO C Incremental build Packages Wrapper classes gtgtgt zerofilling right shift o and on floats and doubles Automatic conversion from char to Strings Labeled breaks finally SECURITY Casts are always checked at runtIme Array bounds checking Automatic implicit initialization Local variables checked for set before use Automatic implicit garbage coHec on PORTABILITY AND IMPLEMENTATION Virtual machine specification Byte codes Lengths of builtin data types machine independent Incremental loading NEW FEATURES FOR JAVA 15 New naming scheme Java 5 Tiger New features Autobox and autounbox Generics for each statement Varargs Formatted IO Enumerations Static imgort Metadata API changes SDP N9 FNPS N9 2 GENERICS Parameterized declarations Methods classes and interfaces Homogeneous collections without explicit downcasting Java Collections framework Type safety and cleaner code GENERIC DECLARATIONS Use ltgt to provide type parameter class fooltTgt fooltThreadgt x Acts as if a new class fooltThreadgt were added to the program Actually the compiler plays games erasure to convert the generic declaration and use into Java 14 code Only class types allowed as parameters not primitives There may be multiple generic parameters EXAMPLE class FooltTgt T x instance variable FooT y X y constructor T getFoo return X getter String whoAmI reflection return XgetClassgetName EXAMPLE USE FooltDoublegt dbl dbl new F00ltDoublegt42 box double d dblgetFoo unbox dblwhoAmI JavalangDouble GENERIC METHODS A method may be generic even if its class is not Actual arguments of calls need not appear in angle brackets They are inferred by compiler Similar to Ada Same for constructors EXAMPLE class Foo Note type parameter before return type ltTgt int barT V return vsize HOMOGENEOUS COLLECTIONS Java collection classes have been reengineered as generics with a parameter to indicate the type of the collected element Automatic enforcement on addition to a coHec on Downcasting not explicitly required on extraction lterators have likewise been made generic 3for each Syntactic improvement to Iterators for type iterationvariable composite statement Works on arrays and collection classes Compare for int lv collection sum lv With IteratorltIntegergt lv collectioniterator while lvhasNext Integer i lvnext sum i 4 VARARGS Methods containing an indefinite number of arguments can now be defined and called On the call side the argument list conceptually has two parts Head fixed number of variously typed arguments as in previous versions of Java Tail Indefinite list of arguments all of the same type Both parts are optional On the calling side the called method looks like a collection of overloaded methods On the called side the tail acts like an array But there is new syntax EXAMPLE int fooint x any number of int args int sum O for int i x can use for each on args sum i return sum fool Length one fool 2 3 foo Empty array 5 FORMATTED O Formatter class 0 printf method in PrintStream and PrintWriter classes using Formatter Scanner class for input sources of input are classes implementing Readable interface 6 ENUMERATIONS Classes with constructors methods and instance variables New keyword enum enum Media TV Radio Magazine Newspaper Enumeration constants are public static final members having the same type as the enumeration Don t call new Instead use primitive declaration Media news 7 STATIC IMPORT 0 import static java lang Imports static members of a class avoids name qualification Single name or Danger of ambiguity when used on more than one import 8 METADATA Program annotation No effect on semantics Intended for tools Associated with declarations such as classes methods instance variables local variables arguments to methods and other annotations symbol prefixes declaration and use EXAM P LE Declaration interface MethodAnnotation method list may be empty marker String message may be defaulted int errorCode likewise Use annotating a method Note that message now looks like instance variable MethodAnnotationmessage My favorite method errorCode 101 void methl OCL iject Qonstraint Language Official part of UML Strongly typed declarative specification of system properties Assertions collection classes UML diagram navigation Supported by Rational Rose ArgoUML PoseidonOctopus Enterprise Architect Why UML diagrams as a graphical language are limited in what they can express Structural relationships behavioral descnp ons The language needs a mechanism for specifying precise semantics OCL extends UML with Class invariants Operation pre and post conditions Guards on statemachine transitions OCL Overview Pure expression language Focus on values no side effects expressible Declarative not procedural No control flow mechanisms Strongly typed Builtin types plus types introduced in diagrams Highest level mechanism is the constraint Uses of OCL As a query language To specify invariants on classes and types in the class model To specify type invariant for Stereotypes To describe pre and post conditions on Operations and Methods To describe Guards To specify target sets for messages and actions To specify constraints on operations To specify derivation rules for attributes for any expression over a UML model Syntax context ltidentifiergt ltconstraintTypegtz ltBoolean expressiongt context is a keyword indicating the start of a new constraint ltidentifiergt is a class or operation name The current position from which relative path names are derived ltconstraintTypegt iS inv pre or post ltBoolean expressiongt iS usually an equation asserting a property Invariants Statement of a property that is always true Except perhaps in the middle of the execution of an operation Expresses a key system requirement inv keyword Might be an essential relationship among the values of the attributes of an object Might express a relationship between classes The student registration system never allows a student to be registered for two classes that meet at the same time context Company inv selfnumberOfEmployees gt 50 Pre and Post Conditions UML operation semantics can be expressed using pre and post condition constraints The pre condition says what must be true for the operation to meaningfully take place The post condition expresses what is guaranteed to be true after the operation completes About the return value About any state changes eg instance variables pre can be used to distinguish the value of an instance variable before an operation from the value aftenNards Pre and Post Conditions 2 The argument to the square root routine must be nonnegative The square of the computed result must equal the argument context Personincomed Date Integer post result 5000 OCL Builtin Primitive Types type values operations Boolean true false and or xor not implies if then else Integer l 5 2 34 26524 abS Real 15 314 floor String 39to be or not toUpper to be concat OCL Keywords keyword description inv pre post Introduces constraints if then else endif Conditional expression not or and xor implies Boolean operators package endpackage Packages context Modifies use of names def Global definition let in Local definition derive Attribute derivation init Initial value description attr oper result Result value from an operation let Clause A let clause is a way of introducing an abbreviation It has two parts both expressions The first part between indicates one or more names and binds values to them The second part is like a local block it limits the scope of where the bindings apply let income Integer selfjobsalary gtsum in if isUnemployed then income lt 100 else income gt 100 endif Navigation OCL constraints are associated with class model diagrams They can also be associated with statecharts Each constraint specifies a context A specific class or method relative to which other diagram elements can be designated Navigation is done by walking through a diagram from the context class to another diagram element using intermediary relationship lines and class rectangles Each step adds a name to a list separated by penods Multiplicity When an association has multiplicity greater than one the result of a traversal is a collection set bag or sequence If an operation is performed on that association the gt symbol is used rather than the period to separate the collection from the operation Collections OCL features four kinds of collections that support associations with manytomany and onetomany multiplicities The parent class Collection provides features that hold true of all collections size includes count includesAll isEmpty notEmpty sum exists forAll and iterate Set Bag multiset and Sequence ordered multiset provide specialized operations Refinements All design involves refinementmoving from a highlevel understanding to an implementation Multiple layers may be involved notjust two depending on the complexity of the problem To execute a multilayer design properly three properties must obtain 1 2 3 The top layer must faithfully represent the requirements Each layer must be internally consistent Each layer must faithfully represent the layer above it Valid Refinements Designer needs to demonstrate that the implementation satisfies the specification This demonstration can be expressed using a set of verification conditions sometimes called proof obligations The demonstration itself can be formal or informal depending on the process used Exercise Assumptions The requirements are expressed as a UML analysis model We are concerned with the specification of a single class A We are only concerned with functional requirements Question 1 What should our specification of this class include Exercise Assumptions The requirements are expressed as a UML analysis model We are concerned with the specification of a single class A We are only concerned with functional requirements Question 1 What should our specification of this class include Attributes types sizes properties etc Operations signatures prepost conditions Invariants over the attributes Exercise 2 Property 1 states that our specification for class A must match the requirements Question How would we normally accomplish this Exercise 2 Property 1 states that our specification for class A must match the requirements Question How would we normally accomplish this This property is usually checked via some form of review either individual or meeting Exercise 3 Property 2 states that each level must be internally consistent Question How can we demonstrate the consistency of class A Exercise 3 Property 2 states that each level must be internally consistent Question How can we demonstrate the consistency of class A Make sure that each operation maintains any invariants Notation P1 P2 Pn are operations in the abstract specification S is a set of abstract states 5 is an element of S combination of attribute values 5 39 is the abstract state s after an operation has completed inv is any invariant invA is any invariant of the abstract spec and invc is any concrete invariant Pre Pi s args are the precondition for operation Pi when executed in state s with arguments args Post Pi s args 5 39 res are the postcondition for operation Pi after execution beginning in state s with arguments args resulting in state s39 with results res 1 Valid Operations Within any given specification either abstract or concrete operations must preserve invariants That is if the invariant is true before execution and the operation terminates then the invariant is true after execution invs A Pre Pis args Post Pis args 839 res ltgt invs39 Exercise 4 Property 3 states that each layer must faithfully represent the layer above This implies checking the mapping between the abstract layer and the concrete refinement Question What checks do we have to make concerning this mapping Exercise 4 Property 3 states that each layer must faithfully represent the layer above This implies checking the mapping between the abstract layer and the concrete refinement Question What checks do we have to make concerning this mapping Each abstract state must be refined into at least one concrete state That is the representation is adequate The concrete layer can t get into a state that doesn t correspond to an intended abstract state That is the representation is total Each abstract operation must be faithfully modeled by a concrete one More Notation Q1 Q2 on are concrete operations corresponding to P1 P2 Pn t is a concrete state a state over concrete attributes within state set T retr is a function that maps from concrete states to the corresponding abstract states That is retr t s where s is the single abstract state that corresponds to concrete state t 2 Adequate Representation A refinement must be adequate That is the implementation must be rich enough that each abstract state is represented by a concrete state In other words for each abstract invariant if the invariant is true in that state then there must exist a corresponding state in the implementation in which the invariant is also true Vs E S invs gt Elt E T invCt A s retrt 3 Total Representation We must make sure that refinements don t produce states that are meaningless with respect to the abstract spec ca on There may be many concrete states corresponding to a given abstract one but each concrete state must somehow be meaningful with respect to the abstract spec ca on That is the retrieve function must be total Vt E T invCt gt 38 E S s retrt A invAretrt Operations To refine operations we must assure ourselves of two things The implementation must be able to handle all inputs described in the specification The output produced by the operation along with any changes made to class attributes must satisfy the operation specification 4 Operation Modeling Circumstances acceptable to the abstract specification must be acceptable to the concrete implementation That is refinements can weaken the pre conditions run under wider circumstances A Vt E T invCt pre P retrt args 1 A ll t args A Pre Q l 5 Models 2 Execution of the implementation must leave the system in a valid state that corresponds to what the abstract specification dictates That is concrete post conditions must imply abstract post conditions A Vt E T invCt Pre Qit args A Post Qit args t39 res gt Post Piretrt args retrt39 res The Mark IV Special Coffee Maker The Mark IV Special makes up to 12 cups of coffee at a time The user places a filter in the filter holder fills the filter with coffee grounds and slides the filter holder into its receptacle The user then pours up to 12 cups of water into the water strainer and presses the Brew button The water is heated until boiling The pressure of the evolving steam forces the water to be sprayed over the coffee grounds and coffee drips through the filter into the pot The pot is kept warm for extended periods by a warmer plate which only turns on if there is coffee in the pot If the pot is removed from the warmer plate while water is being sprayed over the grounds the flow of water is stopped so that brewed coffee does not spill on the warmer plate Hardware Interface The heating element for the boiler It can be turned on or off The heating element for the warmer plate It can be turned on or off The sensor for the warmer plate It has three states warmerEmpty potEmpty potNotEmpty A sensor for the boiler which determines whether there is water present It has two states boilerEmpty or boilerNotEmpty The Brew button This is a momentary button that starts the brewing cycle It has an indicator that lights up when the brewing cycle is over and the coffee is ready A pressurerelief valve that opens to reduce the pressure in the boiler The drop in pressure stops the flow of water to the filter It can be opened or closed Exercise Assume the existence of a lowlevel API that actually controls the various devices Design a set of 00 classes to control the coffee maker Prepare UML classmodel diagram describing your design public interface CoffeeMakerAPI public static CoffeeMakerAPI api null set by main This function returns the status of the warmer plate sensor and whether it has coffee in it public public public public This sensor detects the presence of the pot int getWarmerPlateStatus static final int WARMEREMPTY 0 static final int POTEMPTY 1 static final int POTNOTEMPTY 2 This function returns the status of the boiler switch The boiler switch is a float switch that detects if there is more than 12 cup of water in the boiler public int getBoilerStatus public static final int BOILEREMPTY 0 public static final int BOILERNOTEMPTY l This function returns the status of the brew button The brew button is a momentary switch that remembers its state Each call to this function returns the remembered state and then resets that state to BREWBUTTONNOTPUSHED Thus even if this function is polled at a very slow it will still detect when the brew button is pushed rate public int getBrewButtonStatus public static final int BREWBUTTONPUSHED 0 public static final int BREWBUTTONNOTPUSHED l This function turns the heating element in the boiler on or off public void setBoilerStateint boilerStatus public static final int BOILERON 0 public static final int BOILEROFF l This function turns the heating element in the warmer plate on or off public void setWarmerStateint warmerState public static final int WARMERON 0 public static final int WARMEROFF l This function turns the indicator light on or off The indicator light should be turned on at the end of the brewing cycle It should be turned off when the user presses the brew button public void setIndicatorStateint indicatorState public static final int INDICATORON 0 public static final int INDICATOROFF l This function opens and closes the pressure relief valve When this valve is closed steam pressure in the boiler will force hot water to spray out over the coffee filter When the valve is open the steam in the boiler escapes into the environment and the water in the boiler will not spray out over the filter public void setRelieralveStateint relieralveState public static final int VALVEOPEN 0 public static final int VALVECLOSED l Traditional Approach The traditional 00 approach to doing modeling is to search for nouns in the problem statement and model them with classes After doing this and analyzing the results the following list of terms is obtained filter holder receptacle water strainer button warmer plate warmerplate sensor boiler switch float switch brew button momentary switch state heating element boiler indicator light brewing cycle pressurerelief valve steam pressure boiler Class Model Diagram From such a list and our knowledge of the domain we can construct a highlevel class model diagram Martin39s original version is presented on the following slide CoffeeMaker WarmerPlate BoilerSensor BoilerHeater PlateH39eater PlateSensor V m Problems Missing methods Vapor classes Imaginary abstraction God classes Missing user interface Missing Methods Martin didn39t include any methods in his diagram and then he complains about their lack What is really going on is an artificial emphasis on structure at the expense of behavior Vapor Classes The Light class exists because of the need to control the hardware light But there is no software state In fact the class itself is just an adaptor for the API The same observation holds for Button Boiler and WarmerPlate Imaginary Abstraction Martin notices that Heater and Sensor act as base classes but are not used But isn39t this what factoring is all about But he notices that there is little if any code to actually factor God Classes When the previous criticisms are taken into account the only substantive class remaining is CoffeeMaker This situation is sometimes called a God Class and is generally frowned upon Alternative Approach Start with Use Cases An alternative approach to the above is to write out Use Cases Simple stories illustrating a single execution or pointing out an important obstacle What use cases can you come up with Alternative Approach Use Cases 2 An alternative approach to the above is to write out Use Cases Simple stories illustrating a single execution or pointing out an important obstacle What use cases can you come up with User pushes brew button Containment vessel not ready Brewing complete Coffee all gone Representation of Use Cases Usually a Use Case is textual Eitherjust a short paragraph Or a sequence of ActorActionObject triples UML provides several diagram for denoting Use Cases Collaboration diagram object diagram with ordered labeled transitions Sequence diagram time ordered message passing Note that a Use Case diagram is a way of expressing context by organizing a set of Use Cases CRC Cards A CRC card is an informal way of describing what you learn from a set of Use Cases CRC stands for ClassResponsibilityCollaborator Each card corresponds to on participant in a Use Case Listed on the card are that class39s responsibilities and any necessary collaborating classes The contents of a card grows as more Use Cases are considered Collaboration Diagram Example What must happen in the coffee maker when the user presses the brew button First list the steps the coffee maker must take Then draw a UML collaboration diagram expressing these actions Collaboration Diagram 2 A collaboration diagram for the first Use Case User pushes brew button is shown on the next slide Note that the rectangles are objects not classes Arrows are annotated with numbered method names Arguments may be provided Collaboration Diagram User Pushes Brew Button 1 IsReady gt User Interface Hot Water Source 2 IsR ady gt Containment Vessel 3 Start gt Collaboration Diagram for Use Case 2 Containment Vessel not Ready U eL edaoe tk JNaEinuuoe gu a unenLybssel 1 Start 2Pausegt 3Reswnegt Collaboration Diagram for Use Case 3 Brewing Complete Collaboration Diagram for Use Case 4 Coffee All Gone o H s 1quot I I I I 39 I U 39 TH 39lf v 39 V V O TL39 Roles Each of the objects in a Collaboration diagram can be though of as playing a role in that particular collaboration For example ContainmentVessel sometimes plays the role Of StatusReporter If Collaboration diagrams were drawn for each Use Case then the sum of the roles for a given object describe that object39s overall responsibilities That is the object39s features can be synthesized from the roles it plays Inferred Abstract Classes Hut Wain Usm Irtc hue Sauna Cnmtmo Maul Refinement The class model diagram represents the design of a set of related coffee makers We still have to design the Mark IV We want to do this in such a way that we don39t compromise abstraction None of the three classes we have created must ever know anything about the Mark IV This is the Dependency Inversion Principle DIP We are not going to allow the highlevel coffee making policy of this system to depend upon the lowlevel implementation Martin Abstraction Just like abstract classes can be inferred from a set of related classes so too can abstract roles be inferred If we represent an abstract role with an Interface then we can make these roles tangible and reusable That is a given class is nothing more than the sum of the implementations of the various roles it plays This is a simplified description of so called Role Based Design Solution The solution approach is to add specific interfaces for the Mark IV that inherit from or implement our abstract classes We can also factor out the specific communication mechanism by which the sensors are accessed Behavior Modeling Class models express properties that are true of a system at all times Although they are general they fail to convey interesting behavioral aspects of systems That is how objects respond to external stimuli A variety of alternative modeling techniques are available in UML for behavior modeling Use case diagrams sequence diagrams statechart diagrams activity diagrams timing diagrams interaction overview diagrams communicationscollaboration diagrams Modeling Alternatives Combinatorial Concurrent Control COH EFOI State charts Decision tables Petri Nets Decision trees Activity diagrams Sequential Control Sequence State transition d39agrams tables Collaboration Finite state d39agrams machine Temporal logic Process algebra Combinatorial Modeling The simplest form of behavior modeling merely expresses the logic of simple combinatorial systems In these systems only the inputs and not the history of previous states determines subsequent states Two equivalent forms of combinatorial modeling are decision tables and decision trees Decision Tables One common way to model control is with decision tables They are used when a number of possible input conditions hold and a number of responses are possible The conditions are called inputs and the responses are called outputs The input side of the table enumerates all possible combinations of conditions For example if each of three switches can have one of two possible talues quotonquot or quotoffquot then the table will contain three columns and eight rows Likewise if the three switches control two output devices one switch is a master override then there will be two output columns along with the eight rows from the input Example Decision Table 1 INPUT Output Master Light Power Control Switch Switch L39ghts Motor ON ON ON ON ON ON ON OFF ON OFF ON OFF ON OFF ON ON OFF OFF OFF OFF OFF ON ON OFF OFF OFF ON OFF OFF OFF OFF OFF ON OFF OFF OFF OFF OFF OFF OFF Condensed Decision Table Note that the last four rows of the output are identical The table can be shortened by making use of quotdon39t carequot entries A don39t care entry is indicated by clashes in an input cell INPUT Output Master Light Power Control Switch Switch ON ON ON ON ON ON ON OFF ON OFF ON OFF ON OFF ON ON OFF OFF OFF OFF OFF OFF OFF Light Motor Decision Trees A decision tree contains the same information as a decision table but in graphical form There are two kinds of nodes Diamonds denote decisions Rectangles denote actions to be taken Labeled arcs indicate the implications when a decision is answered in a particular way affirmative or negative Note that some nodes may be duplicated Example Decision Tree Controller On Light Off Motor Off Light On Motor On Light On Motor Off Light Off Motor On Light Off Motor Off Incorporating History Combinatorial descriptions suffice when time is not a factor that is when the history of previous system activities does not affect future behavior Many systems however do have this property and a useful abstraction for reasoning about such systems is the idea of state Systems with state are called nite state systems and can be modeled with finite state machines and their variants States A state is an abstract summary of the set of values for system attributes at a given instance A condition or situation during the life of an object during Which it satisfies some condition performs some activity or waits for some event UML Reference Manual The state of a system varies as it performs operations The set of all possible states of a system is called its state space What is the size of a state space Events At any given moment an object is in exactly one state An object39s state can change in response to a stimulus for example the execution of an operation The term used to describe an atomic stimulus is an event The event can lead to a change of state called a transition Events can be synchronous or asynchronous Events can occur as the results of actions the user hits a button data conditions the temperature gets above 90 or the passage of time UML Event Taxonomy Signal asynchronous notification Method ca synchronous operation invoca on State change continuously monitored Time passage State Transition Table STT Rows correspond to states and there are four columns Name Input event a given state may need to have several rows one for each allowable input event Output actions Next state That is a state transition table captures the idea that a system in a given state receives an input event takes action upon it possibly producing an output and then moves into another state STT for Garage Door Opener Current State Input Action Next State D CI d oor ose Button Pressed Start Motor Motor Running Up Motor Off Door Open Door Open Motor Running Up Detected Stop Motor Motor Off D P rt39 0 Motor Running Up Button Pressed Stop Motor oor a la y pen Motor Off D P rt39 0 oor a la y pen Button Pressed Start Motor Motor Running Down Motor Off D 0 M21 gffn Button Pressed Start Motor Motor Running Down D CI d D CI d Motor Running Down oor ose Stop Motor oor ose Detected Motor Off Motor Running Down Button Pressed Stop Motor Door Partially Closed Motor Off D P rt39 CI d oor a la y ose Button Pressed Start Motor Motor Running Up Motor Off Variants on State Transition Tables Note that the four factors represented in an STT can be presented in a variety of ways Row and column are state and input contents are action and next state Row is state column is next state content is input and action The most common variant however is to express state transitions in a diagram called a state transition diagram State Transition Diagrams A system39s states and events are most commonly modeled as a finite state machine a directed graph where nodes correspond to states and arcs correspond to transitions Diagrams denoting finite state machines FSMs are called State Transition Diagrams State are denoted by labeled bubbles ovals or rectangles A state transition diagram is always in exactly one state ie it is deterministic When an input event occurs the machine moves to another state and optionally performs an action States are connected by labeled directed arcs denoting the transitions among the states The labels on the arcs consist of two parts The first is the event provoking the transition The second is any action performed during the transition State transition diagrams contain exactly the same information as state transition tables The layout of nodes and arcs has no semantic import Example Garage Door Opener Door Closed Motor off button pressed Start m t r door closed detected stop motor Door Partially Closed start motor Motor Runnlng Motor off Up button pressed stop motor button pressed Door Partially Open stop motor Motor off Motor Running button pressed start motor Down door open detected stop motor utton pressedl start motor Door Open Motor off Notes Transition arcs have two parts either of which may be empty First is the event stimulating the state transition Then comes an action that is performed as part of the transition The two parts are separated by a in this diagram Sometimes they are aligned vertically with a horizontal line separating them Example Telephone Number dialed k un dialed Handse umber lifte Ha set a r laced replaced set In use replaced Ca ee ndset an ers replac s llee hangs I Notes One of the states ON HOOK is denoted with concentric circles In this case it indicates that the state is the initial state of the system The DIALING state has a transition back to itself The fact that dialing itself has many states has been abstracted out of this diagram There is a great deal of duplication in the diagram Problems with State Transition Diagrams Too many arrows n2 with 17 states and 17 events Too many states 2m with m concurrent activities No concept of abstractionnesting Statecharts Examples from the URM and the Harel paper One problem with finite state machines is the explosion in the number of states that occurs when several independent activities are going on simultaneously Also traditional state transition diagrams provide no mechanisms for abstraction the grouping together of related states that are relatively independent from the other states in a system David Harel developed an extension to finite state machines called statechan s to overcome these difficulties Statecharts have been added to UML to support behavioral modeling of reactive systems Statechart Icons OffHook dropConnection State roundtangle May have names Transition solid line with open arrowhead May be labeled May have actions Default initial state gt Final state Active Statechart Extensions to FSMs Depth composite sequential state machines Concurrency composite concurrent state machines Broadcast definition and generation of new events Default states initial and final Conditional guarded transitions History Entryexit actionsactivities Event parameters Statechart Nesting o b A line exiting from a composite state d stands for a set of lines coming from all of its interior nodes eg f A line entering a composite node from its exterior implicitly terminates at its default interior node h Example shutDown tooCoIddesiredTemp tooHotdesiredTemm atTemp Heating Activating tooHotdeSIredTemp Cooling ready turnOn tooColddesiredTemp Example Active Validating cardlnserted cancel maintain Maintenance continue Selecting Processing not continue Pnn ng entry readCard exit ejectCard Note guards Entry actions occur on state entry Exit actions occur before leaving Statechart Concurrency Joins and splits denote and Guarded transitions with square brackets and predicates in 0 Example maintain Maintenance Testing lt3 Commanding continue keyPress Broadcast Cascaded Events I II l I l r I I I l I I I I l 39 3 0 L Transitions can cause new events to take place They appear after a slash How many different transitions might be the result of event 17 Special Transitions Time and Change Events when 11 49 SeltTest after 2 seconds dropConnection Idle Active Time after 2 seconds Change when time 1159 Boolean Continuous evaluation Example Transitions after 2 seconds send cisAIive Searching Engaging targetAtpisThreat taddTargetp contact Tracking Engaged Note event parameter p History States query Upon second and subsequent entries into BackingUp the system will commence in the state issuing the last query The concept of deep history H is also supported This mechanism takes into account state nesting BackingUp Collecting Copying CleaningUp Complete UML State Description Entry action Tracking W Exit action entry setModeonTrack Internal transition exit setModeoftT rack newTarget trackerAcquire Activity 939 do followTarget seIfT est defer Deferred events Notes State machine for a class can be inherited from a superclass What does this mean if the subclass also has a state machine Actions are atomic behaviors that is they do not take any time and therefore have no semantic implications on the statechart Entry actions are performed outside in exit actions inside out Activities are behaviors requiring significant duration The word activity is longerthan the word action Deferred events are delayed as far as this state39s processing is concerned Internal transitions have actions but do not result in a change of state No entry or exit actions take place Complete UML Transition Description Source state Trigger event may be null Guard boolean may be null Action may be null Target state Forks and joins allowed in diagram Relationship to Class Diagram Each class may have a statechart Signals may appear on class diagrams Dependency exists between class that can send a signal and the signal class Receivable signals can be placed in an extra class compartment MovementAgent send position si nal g veIOCIty CoIIISIon moveTo in force float UML Event Taxonomy Signal asynchronous notification Method ca synchronous operation invoca on State change continuously monitored Time passage UML Signals Asynchronous communication between objects Just another class ltltsignagtgt stereotype May have parameters May have subsuperclasses signal OffHook Harel39s Digital Watch 2 mm um Wynnwulmn mmmur ammo WW W W amme upmmm HighLevel View of Digital Watch W1 39inuuw I lmudm Ln Inch enob cliniularmn c l thanh d miniormi I I mlchimen L l h of Mom Stop Watch State stopwatch Q5quot fquot y N chime on I run an m alumna Do I a I W l Displays State rdtwlnys 1mm 4 Mommamull Petri Nets Longstanding graphical notation for expressing process synchronization States are called nodes or places Denoted by circles Can contain tokens Arcs carry tokens between states Bars denote transitions Bar can39t be passed unless all adjacent incoming states contain tokens Tokens merge on fan in replicate on fan out Expressible in UML via Activity Diagrams Token Merging Before After Conveyor Belt Synchronization Truck arrives at Paperwork ConVeyor belt Conveyor belt moving FiniShed QOOdS loading dock with processed mOVing raW 900d finished goods from loaded on truck raW QOOdS from loading dOthO factory to loading doc Mnrehnl 1S9 BoxOfficezzReceiveOrder UML Activity Diagram Example States Completion transitions Object flows not shown Swim lanes not shown transient create I 4Jlansagiign setActionsa d o committed ltltdestroygtgt p ODBCProxy setValuesd 34 setVaIuesa quotCOquot Sequence Diagram Q 3 ltltdestroygt gt 2 cqnmitted setActiona d o IOC5I l 1 ltltcreategtgt Collaboration Diagram Version 21 setVaIuesd 34 gt 22 setVaIuesaquotCOquot gt mm m a Architectural Documentation View summary data presentation Graphical tabular textual Kruchten39s 41 Views Philippe B Kruchten quotThe 41 View Model of Architecturequot IEEE Software 12642 50 November 1995 Logical developmental process physical use case Features nonfunctional requirements bug reporting context utility Logical View Structural breakdown of computational communicational and behavioral responsibilities Diagrams Box and arrow Components and connectors ADLs UML Class model diagram UML Interaction Overview diagram UML Collaboration diagram Developmental View Units of source code Packages classes subsystems libraries files Diagrams UML Package diagram UML Component diagram CVS modules Example Class Diagram with Packages su bsys em subs Hm kage made of packages pats b wjgeefhz Ordering e 7 dzpanden x W W External Storage 4 gt package packs Package Diagram m LDg u Vmw rm oamuy Component CardAgency CreditCardCharges TicketDB Managerlnterface TicketSeller o groupSales Supervisor Kiasklnterface Clerklnterface Diagram Process View Processes and threads into which execution is divided Diagrams UML Deployment diagram Example Eg Deployment ssss Diag ram clientMaChine PC Physical View Machines used for system execution and how processes are allocated to them Diagrams UML Deployment diagram UML Sequence diagram transient create I 4J1ansa91ien setActionsa d o l committed p ODBCProxy setValuesd 34 setVaIuesa quotCOquot Example Sequence Diagram Use Case View Important execution sequences from the external actors39 points of view Diagrams UML Use Case diagram UML Communication Collaboration diagram UML Sequence diagram UML Activity diagram Structured text Example Use Case Diagram pdate ccount Account ng System Analyze Risk Trading Manager Trader Limits Exceeded Salesperson E IOC5I J 7 E Equivalent AZ Collaboration Diagram 2 cqnmitted 21 setVaIuesd 34 gt 22 setVaIuesaquotCOquot gt mm m 1 BoxOfficezzReceiveOrder Set up order single order Assign seats subscription member Award member bonus Charge credit card Debit account Mail packet Example Activity Diagram Feature View Conceptual units from the user39s point of View Diagrams Feature diagram Interfeature constraints Example Car 0 I Pulls Trailer Car Body I I Transmission I I Engine Automatic I I Manual I I Electric I I Gasoline Notation Mandatory features Optional features Alternative features Choose exactly one Or features Choose a subset A A NonFunctional View How nonfunctional requirements affect the software architecture Explicit tradeoffs Tabular text Bug Reporting Units to which bugs are allocated Consequences with respect to Developmental View Consequences with respect to Feature view Bugzilla components Context View Relationship of a system to its environment External actors events and percepts Data flow Context Diagram Context Diagrams The top level data flow diagram is called the context diagram It contains exactly one process node denoting the overall function of the system Human Moves Human Opponent Machine ives Board Drawings Utility View Supporting software Installation scripts Log file analysis Statistical processing Tabular text Modeling with UML 14 Class Model Diagrams UML class model diagrams are commonly used to represent the structural aspects of system design problems A class diagram consists of a collection of object classes and the relationships among them Classes A class is a distinct object type participating in the system being built A common noun in English often indicates an object type A class is represented by a rectangular box possibly partitioned into three parts vertically ie separated with horizontal Hnes Class name Attributes Operations Class Features Classes have features attributes and operations While objects and classes exist in the real world or in the mind of the designer features exist inside of the computer An attribute is a property of a class Typically attributes have types that correspond to primitive or composite data types available on the computer An operation method is a service provided by an object It may take typed parameters and possibly return a typed value Relationships Relationships exist among classes and they are represented by lines connecting the related classes UML class model diagrams have three kinds of relationships Generalization Dependency Association Library Information System This exercise asks you to create a UML class diagram that models the problem of managing the information resources for a library That is devise an analysis model Assume that somebody else will be designing the program from your analysis Include classes their attributes and operations and the relationships among them Indicate attribute types cardinality of associations generalization and aggregation relationships 10 11 Library Problem Requirements Each patron has one unique library card for as long as they are in the system The library needs to know at least the name address phone number and library card number for each patron In addition at any particular point in time the library may need to know or to calculate the items a patron has checked out when they are due and any outstanding overdue fines Children age 12 and under have a special restriction they can only check out five items at a time A patron can check out books or audiovideo materials Books are checked out for three weeks unless they are current best sellers in which case the limit is two weeks AN materials may be checked out for two weeks The overdue fine is ten cents per item per day but cannot it go higher than the value of the overdue item The library also has reference books and magazines which cannot be checked out A patron can request a book or AN item that is not currently in A patron can renew an item exactly once unless there is a outstanding request for the item in which case the patron must return it Linguistic Analysis One approach to dealing with a problem such as this is to linguistically analyze the text of the problem description This approach was developed independently by Abbott and by Booch In particular nouns will map to classes active verbs will map to operations certain stative verbs will map to relationships and adjectives and adverbs will map to attributes Nouns in Requirements One approach to beginning the modeling process is to review the requirements looking for nouns as candidate classes When we do that for the library problem we get the following possibilities patron library card system library name address phone number time item fine libraryCardNumber child restriction book AVMaterial week bestSeller limit day cent value reference book magazine request age Candidate Classes From these nouns with can identify some that are good candidates for classes We may have to merge some synonyms in doing this Patron Child Item Book LibraryCard System Library AVMaterial ReferenceBook Magazine BestSeller Fine Request Remaining Nouns to be Considered name address phone number time fine libraryCardNumber restriction week limit day cent value age Attributes Some of the remaining nouns map naturally to attributes of the identified classes name address phoneNumber Patron age Child libraryCardNumber LibraryCard Remaining Nouns to be Considered time fine restriction week limit day cent value Utility Classes Some nouns belong to classes but the classes are more general than just this one problem We can imagine them belong to a library Date time week day limit Money fine cent value Remaining Noun to be Considered restriction deferred until we have a better understanding of the problem Inferred Attributes Sometimes we can identify missing elements of our model and introduce model elements for them For example we can infer some missing attributes from the requirements dueDate Date Item It is a natural part of an analyst39s job to point out missing confusing or incorrect parts of an initial requirements document Operations We can perform a similar analysis on verbs Active verbs often indicate operations that we can assign to classes query of the itemsCurrentlyCheckedOut query of whenDue query to computeOverdueFines checkOut request renew return Stative Verb Another category of verb is called Verbs of this type descriptive rather than indicating actions For example the stative verb phrase is a kind of or just is a indicates a generalization relationship Likewise is a part of comprises or has a are indicative of aggregation associations Associations Other stative verbs may indicate general associations For example the idea of a patron checking out an item from a library suggests an association between Patron and Item Hence it makes sense to treat it as an association CheckedOut Likewise for Re que 5 t Aside Scenarios A different approach than linguistic analysis is to write use usage scenarios use cases user stories The scenarios can then be used to generate CRC class responsibilitycollaborator cards Eg an actor in a scenario becomes a candidate class Sample library scenarios include the following A patron checks out 3 books and 1 av material A patron attempts to renew a book A librarian runs a report of all patrons with outstanding overdue fines A patron attempts to request a book A book is returned A child attempts to check out 7 books Missing Requirements In performing this analysis other unstated requirements may surface that should be confirmed with the customer The system should provide operations for the Patron to make or cancel a request The system should provide an operation for a Patron to renew an Item The system should allow a Patron to pay a fine The system should be able to to determine whether or not an Item can be checked out The system should be able to determine whether an Item has been renewed Possible Class Model Diagram Patron 39 String 39 Llquot libraryCardNumber String computeOverdueFines 1 Money itemsCurrentlyCheckedOut 1 SetLoanabetem checkOut in i Loanableltem enDue in i Loanableltem Date return in i Loanableltem renew in i Loanableltem cancelRequest ant Title payFine in item Loanableltem Title name String name 39Str39ng 4 Requests address String author Strlng t isbn String 4 birthDate Date 1 age Date CheckedOut hasBeenRenewed Boolean false Item dueDate Date ne 1 Money request in t Title whenReturned Date 0 W Loanableltem EerDayFine Money 10 alue Money A A 3 Ihnetgnllnr 39Rnnlnnn I Reference Book utility Money utility utility Date OperatingSystem getDate Date Notes on the Diagram Diamonds on association ends Composition filledin diamond if a Title goes away so does its Items Aggregation open diamond a grouping relationship that doesn39t imply linked lifetimes Class attributes underlined properties of the class as a whole Qualified associations rectangular association end indexes instances Cardinality number of instances at one end that correspond to a single instance at another end Derived attributes slash computed rather than stored Stereotypes ltltnamegtgt metamodel types Default values of attributes assignment Reading direction lt on Requests Issues Raised 1 When does a CheckedOut link get deleted Issues Raised 1 When does a CheckedOut link get deleted That is a Patron can return an overdue Item but delay paying the fine Then the link has to remain but no additional fine need accrue This implies one or more attributes on CheckedOut Whether the Item has been returned boolean and the date of the return Date Alternatively a special Date 0 could indicate that the Item has not yet been returned Associations with features are called association classes Issue 2 The stated requirements really describe a library information system and not a library Hence there is likely no Library class But there may be a LibraryInformationSystem class that contains the other classes Implicit in the diagram It could also be modeled as the name of a package that contains the classes in the diagram Such an approach would be better expressed by replacing Patron With PatronRecord etc This conversion is part of the design process not the analysis process Issue 3 LibraryCard has no independent role Just include LibraryCardNumber as an attribute of Patron Issue 4 Should Child be a subclass of Patron or be determined computationally Issue 4 Should Child be a subclass of Patron or be determined computationally If a separate class is used then a given instance would have to change its class when the corresponding Child reached its thirteenth birthday If childness is computed then we have to have a operation for determining what the current Date is A System class with a getDate operation This means that age becomes a derived attribute and we need a birthDate attribute for Patron Issue 5 ReferenceBooks and Magazines have no features other than that they cannot be checked out This raises the question of whether they couldn39t be modeled with a boolean canBeCheckedOut attribute Of Item Leaving them as classes allows the customer to specify more properties and enables future growth Issue 6 Whether a Book is a best seller however has been modeled with an attribute It could have instead been another subclass Its only current use is in computing the length of the checkout period So an attribute was used instead of a subclass Issue 7 Need operations for creating Items and Patrons Constructors need to be added to the diagram 8 Issue Is it necessary to have separate classes for AVMaterial ReferenceBook Magazine BestSeller Issue 9 It would appear that time week limit and day are related In a situation such as this it is the analyst39s job to invent a class Date that is not explicit in the supporting documents Likewise for Money subsuming cent value and fine Issue 10What is it that a Patron is requesting when they make a Request Issue 10What is it that a Patron is requesting when they make a Request Patrons don39t request Items They really request any one of a set of Items with the same title Hence there is a missing concept in the diagrams a Title That is a Title is an aggregation of Items that share certain properties Issue 11 As modeled a request for a Book eg A Perfect Storm can be satisfied with AudioVideoMaterial the corresponding movie This is likely not what is intended This could be handled by making Request an association class and adding an enumeration attribute to distinguish the book from the movie Issue 12As modeled a user can request a NonLoanableItem Title should contain only Loanableltems Other UML Issues UML supports multiple inheritance which has not been illustrated in this diagram UML encourages the use of role names for the ends of association which don39t appear in the diagram OCL and Constraints If we look back at the original requirements we note that many of them are not satisfactorily addressed by the class model diagram For example the various rules for the length of time which an Item can be checked out are not specified UML has a textual notation called OCL for expressing these kinds of constraints Requirement 6 Books are checked out for three weeks unless they are current best sellers in which case the limit is two weeks This property can be expressed with an OCL constraint called an invariant on instances of class Book A constraint can refer to the values of Book39s attributes It states a rule that must hold for all instances context Book inv if bestSeller then checkoutPeriod 2 weeks else checkoutPeriod 3 endif Exercise Provide an Englishlanguage description of the expected behavior of a routine Y SORT X where X is an input sequence of integers and Y is an output sequence of integers Assume that you are sorting in ascending order SORT in English The output vector Y must be ordered The contents of Y must be the quotsame asquot the contents of X Everything in X must be in Y Everything in Y must have come from X The number of occurrences of each item in Y must be the same as its number of occurrences in X Exercise Now express the same behavior in predicate logic OCL Process 1 Signatures 2 Preconditions 3 Postconditions 1 Signatures You can start the process of formalization by giving the signature for the function or relation that you are defining A signature includes the name of the function the type of the value that it returns and the types of its parameters SORT39S Signature The name of the function is SORT It returns a Sequence Of Integers It takes a single argument of type Sequence OfIntegers So in OCL the signature looks like SORTX SequenceInteger SequenceInteger 2 Preconditions The next step to formalization is to determine what the function39s preconditions are A precondition states what a function requires to be true in order to produce its results SORT39S Preconditions For SORT any input Sequence Of Integers X qualifies Thus SORT iS always able to run Assume that a type checker detects if there are missing or mistyped arguments This precondition is designated as true pre true It can also be left out entirely 3 Postconditions The third step to formalization is to specify the function39s postconditions A postconditions states what must be true after the function has completed its work For pure functions a postcondition describes the computed result in terms of the input parameters For impure functions procedures you should also indicate side effects Changes to global variables Inputoutput For 00 methods changes to instance variables must also be described SORT39S Postcondition SORT39S output has two properties It must be in order The elements must be the same as the inputs We can make use of OCL39s Bag class post ORDEREDY and YaSBag XasBag We will take another approach using permutations post ORDERED Y and PERMUTATION X Y ORDERED Now give a formal specification for ORDERED Signature Precondition Postcondition ORDERED2 Now give a formal specification for ORDERED Signature ORDEREDY SEQUENCE Integer Boolean Precondition Postcondition ORDERED2 Now give a formal specification for ORDERED Signature ORDEREDY SEQUENCE Integer Boolean Precondition pre true Postcondition ORDERED Postcondition In predicate logic we have Vizlsi lt m oym sYi 1 For all positions in Y from the first through the one before the last the value stored in the sequence at that position is no greater than the value stored at the next position Sequences have an indexing operation Indexing of Sequences starts from 1 V reads quotfor allquot lYl is the length on ORDERED Postcondition OCL Y gtforAllel Integer Y gtforAlle2 Integer indeXOfel lt indeXOfe2 implies el lt e2 gt navigates from a Collection forAll is an operation of Collections First comes a bound variable el Then a Boolean expression The overall result iS true if the Boolean expression is true when the bound variable takes on all possible values from the Collection PERMUTAT I ON Now give a formal specification for PERMUTATION Signature Precondition Postcondition PERMUTAT I ON Now give a formal specification for PERMUTATION Signature PERMUTATIONX Sequencelnteger Y Sequencelnteger Boolean Precondition Postcondition PERMUTAT I ON Now give a formal specification for PERMUTATION Signature PERMUTATIONX Sequencelnteger Y Sequencelnteger Boolean Precondition pre X gtsize Y gtsize Postcondition Architectural Styles and Non Functional Requirements Jan Bosch Design and Use of Software Architectures AddisonWesley May 19 2000 Performance That attribute of a computer system that characterizes the timeliness of the service delivered by the system SEI Measures Response time throughput capacity utilization Devices Caching Concurrency Memory management Maintainability Extent to which enhancements can be readily added to a system Also called evolvability flexibility adaptability Measures Coupling Cohesion Devices Encapsulation Published interfaces Subclassing lndirection Wrapping Reliability Likelihood of failure in a given time period continuity of service Measures Reliability Mean Time To Failure MTTF Devices Redundancy fault tolerance recovery blocks Safety Extent to which system protects against injury loss of life or property damage absence of catastrophic consequences Measures Interaction complexity time coupling faulttree analysis Devices Hardware interlocks Fault containment Security Extent to which system protects against unauthorized intrusion confidentiality Measures Levels confidential top secret formal proof Devices Authentificationauthorization Security kernels Encryption Auditing and logging Access control Pipe and Filter Performance Maintainability Reliability Safety Security Pipe and Filter Performance concurrency and buffering enhances throughput but context switches can slow things down Maintainability independent components improves reuse but requirements changes can effect multiple components Reliability reduced reliability due to quotweakest linkquot serial dependencies that is redundancy is antithetical Safety reduced by multiple dependencies but verification may be enhanced because all output comes from a single source Security simplicity increases opportunities for authentification encryption and implementation of security levels Laye ng Performance Maintainability Reliability Safety Security Layenng Performance response to external events must be passed up and down the layers increased context swapping Maintainability stable protocols lead to welldefined and reusable components it may be possible to replace an entire layer Reliability because an event may be quothandledquot in multiple layers reliability is reduced however higher layers may have the oversight to provide redundancy Safety easy to insert safetymonitoring layers Security security layers can be added to intercept and evaluate external events before they can compromise a system Blackboard Performance Maintainability Reliability Safety Security Blackboard Performance lack of welldefined control flows may lead to redundant administrative behavior polling of repository Maintainability independent components enhance flexibility but changes to a common control paradigm or data format may have pervasive effect Reliability independence of components can increase resilience no overall definition of system behavior makes identification of problem situations difficult Safety blackboard can promote spreading of bad data Security access control enhanced because of common data storage but dynamic addition of new components may reduce confidence Object Orientation Pe bnnance Maintainability Reliability Safety Security Object Orientation Performance small objects lead to multiple context switches Maintainability independent components can localize changes but objects store references to each other increasing dependencies Reliability decentralized control reduces opportunity for oversight but encapsulation can reduce vulnerability to unintended interactions Safety correspondence between realworld entities and objects improves intentionality and accountability Security fragmentation negative and encapsulation positive explicit user interface objects can reduce vulnerability Implicit Invocation Performance Maintainability Reliability Safety Security Implicit Invocation Performance extra communications due to bookkeeping and indirection can lead to reduced performance Maintainability increased reuse due to independence Reliability event broadcast enables system wide handling increased interaction complexity Safety interaction complexity Security fragmentation negative and encapsulation positive KWIC Exercise D Parnas quotOn the Criteria to be Used in Decomposing Systems into Modulesquot Communications of the ACM 151210531058 December 1972 Key Word in Context KWIC The KWIC index system accepts as input an ordered set of lines each line is an ordered set of words and each word is an ordered set of characters Any line may be circularly shifted by repeatedly removing the first word and appending it at the end of the line The KWIC index system outputs a listing of all circular shifts of all lines in alphabetical order of the keyword used to shift the line Common stop words may be omitted Circular Shifts Original title Gone with the Wind Circular shifts key words underlined gn with the Wind with the Wind Gone th Wind Gone with Wind Gone with the Stop word removal gn with the Wind Wind Gone with the Example With Multiple Titles Gone with the Wind War and Remembrances 0The Winds of War KWIC Example and Winds of with the The gone Bemembrances ar ar Kind Hinds with the Wind War The and Remembrances Gone of War EXERCISE Parnas Assume that you had to implement KWIC Decide how you would break it into approximately six pieces even if you don39t think it is big enough to have pieces Use a box for each piece and give it a label Ignore stopword removal Decide how the pieces communicate Use a line between two boxes to indicate some form of communication Label the line to indicate the type of communication Come up with at least two solutions For each give circumstances when that solution would be advantageous 1 Shared Data Decomposition Break into components based on the functions computed Also Known As Functional Decomposition All components share access to data in memory Usually contain a mastercontroller routine Dependencies realized with function calls Components Input reads titles stores in memory Circular shifter constructs array of pairs ltine index word indexgt Alphabetizer batch sorting of circular shifts Output Master controller Shared Data H Direct HIM Amos Subpogrlm Call 312 10 A I 39W I cm ar Shift Alphabetizer J Output Hquot Charmer Index A39P gdb uud x Input Output Medium Medium Figure 6 KWIC Shared Data Solution 2 Abstract Data Types ADT Decomposition Organization based on data structures Representation hiding Modules holding data structures also provide services Precursor to object orientation Components Line ADT Input reads titles hands to Line Characters ADT Circular shifter ADT Alphabetic Shifts ADT lth circular shift Output Master controller Abstract Data Type a Samaria Can System V0 Mamr CalmDI Characters Figure T KWIC Abstract Data Type Solution 3 Implicit Invocation Client modules express interest in state changes in server modules registration Server announces changes to all registered listeners broadcast Server does not know identity of clients Unit of notification is the event Components Input of new line Update line data structure Invoke circular shifter Update second line data structure Invoke alphabetizer Implicit Invocation lmidt Invocation quotm Comm smmm System IIO 39 u h Clrtular Input sum Alphabcuzcr Output Figure 3 KWIC Implicit Invocation Solution 4 Pipe And Filter System organized into independent programs lters Each filter takes in input stolin and produces output stdout Filters are connected together via FIFO queues pipes Common assumption of sequential files containing lines of ASCII characters Can you think of a nonASCII example Components Filters for circular shift and alphabetizer Pipe connections with files of FIFOs No common data storage Pipe And Filter Pips SyStImiO I mll ArDhabmmr Output F I Output I Medium Figure 9 h W1C Pipe and Filter Solution Evaluation Shared data Intuitive efficient access Brittle to changes in representation ADT with no data sharing Maintainability reuse Performance Implicit invocation active data Enhancements data representation changes reuse Difficult to controlthink about inefficient Pipe and filter Intuitive reuse Interactivity space efficiency Exercise Continued List at least three possible enhancements improvements that could be made to KWIC For each of the four styles shared data ADT implicit invocation pipe and filter indicate how well it would cope with each of your changes Use the categories brittle moderate flexible to label your choices KWIC Changes Input format New functionality Reuse Stopword elimination 0 Processing algorithm Interactive line deletion Use of external storage Performance optimization Data representation Line storage Explicit circular shifts Indexoffset circular shift Shift each line as it is read Shift lines after all are read Shift lines on demand Incremental versus batch sort Design Patterns A design pattern is a solution to a problem in a context descriptions of communicating objects and classes that are customized to solve a general design problem in a particular context Gamma et al Means of capturing and reusing design knowledge Besides a broad collection of books on design patterns there are also books on analysis and reengineering patterns as well as programming languagespecific pattern books and even a book on antipatterns History The concept of patterns derives from building architecture Christopher Alexander et al wrote the book A Pattern Language in 1977 that described prototypical ways in which building and their rooms are used The seminal book on software design patterns sometimes called the Gang of Four book is Gamma Helm Johnson and Vlissides Design Patterns Addison Wesley 1995 Other information on design patterns including a catalog can be found at http hillsiole netpatterns Example Pattern Name Mediator Category Object Behavioral Intent encapsulate how a set of objects interact Also known as Motivation reduce coupling between objects promote reuse increase intentionality encapsulate collective behavior in a Mediator object Examplecomplex widget dialog Applicability Use the Mediator pattern in the following s ua ons Object interactions are welldefined statically understood but complex Embedding behavior in objects reduces reusability Behavioral customization should be localized Where you want to dynamically alter the interactions among related components Mediator Static Structure Mediator Colleague mediator ConcreteMed iator createColleagueso setDatao Mediator Collaboration aQonoLeierJJaagueJ w 8 g 9 3 6 m 9 o 3 setData More Mediator Participants Mediator defines collaboration interface ConcreteMediator implements dependencies among Colleagues knows of specific Colleagues Colleague knows Of Mediator but not other Colleagues Collaborations Colleagues communicate With Mediator Mediator routes requests Consequences Decouples Colleagues Supports Colleague reuse Simplifies protocols Communication is nowjust to and from Mediator Centralizes and abstracts control Intentionality If collaboration is for the purpose of invariant maintenance there is a single place to look to ensure compliance Limits subclassing to Mediator when customizing collaboration Implementation Issues If Colleagues are interacting with a single Mediator there is no need for an abstract Mediator class Mediator can be implemented as an Observer Register interest with Colleague change causes notification Colleagues can pass self as an argument so the Mediator knows where the event came from Format For Patterns Name captures the concept in a word or phrase Category creational structural behavioral Intent design issue or problem addressed Also known as other names for Motivating scenario illustrates the design problem being solved Applicabilitycontext general description of the situations where the pattern applies Structure static class model diagram Participants description of each of the classes involved Format 2 Collaborations event trace message sequence chart collaboration diagram Consequences tradeoffs what varies Implementation strategy in various languages pitfalls hints techniques Sample code Known uses in existing systems Related patterns often used together Categories Creational object creation and construction Structural composition of classes or objects Behavioral interaction and distribution of responsibility Design patterns can be applicable at either the class or the instance level Design patterns typically enable something to vary Creational Patterns Abstract Factory create families of objects without specifying concrete classes Ul toolkit variants with different looks and feels Application itself does not know about look and feel Builder separate construction of a complex object from its representation to allow representation to vary Factory Method let subclass decide which class to instantiate Framework merely asks for creation specific creation is done by concrete factory Prototype use a prototypical instance rather than a class to guide construction of an object Singleton ensure only one instance of a class is created Creational Pattern Variation Design Pattern Aspects That Can Vary AbStraCt families of product objects Factory i Builder how a compos te object gets created subclass of class that is F t M th 01 ac Cry e O Instantlated class of object that is Prototype instantiated Singleton the sole instance of a class Structural Patterns Adapter convert interface to improve interoperability Bridge decouple abstraction and implementation abstract class contains member that is its implementation Composite complex data structure whose parts have many different types Decorator attach additional responsibility to an object dynamically Facade higherlevel interface for a subsystem Flyweight use sharing to support large number of finegrained objects Proxy control access to an object Structural Pattern Variation 333 Aspects That Can Vary Adapter interface to an object Bridge implementation of an object Composite structure and composition of an object Decorator responsibilities of an object Facade interface to a subsystem Flyweight storage costs of objects Proxy how an object is accessed its location Behavioral Patterns Chain of Responsibility separate request from handler allow multiple handlers Command turn a request into an object logging undo Interpreter represent a grammar and interpret its instances Iterator Enumeration access elements of a collection without exposing the underlying representation Mediator encapsulate object interactions Memento capture object39s internal state for later restore Behavioral Patterns 2 Observer Listener notify dependents when an object changes State class with attribute of type State whose instance tracks current state effectively allows a class to change at runtime Strategy family of algorithms with the same purpose and interface instance is a specific algorithm Template Method skeleton for an algorithm with hooks for specific steps inverted control structure parent calls child rather than vice versa Visitor apply a method to elements of a structure Behavioral Pattern Variation 1 Design Pattern Aspects That Can Vary Chain Of roviders of a service Responsibility p Command when and how a request is fulfilled grammar and interpretation of a Interpreter language how an aggregate39s elements are Iterator accessed traversed how and which objects interact with Mediator each other