DESIGN_PATTERNS_28_04_12_and_05_05_12

Views:
 
Category: Entertainment
     
 

Presentation Description

No description available.

Comments

Presentation Transcript

GRASP PATTERNS:

GRASP PATTERNS T. Sabhanayagham 28/04/12 & 05/05/12

PATTERNS:

PATTERNS A pattern is a named description of a problem and solution that can be applied to new contexts; ideally, it provides advice in how to apply it in varying circumstances, and considers the forces and trade-offs. i.e., Pattern is a named problem/solution pair that can be applied in new context, with advice on how to apply it in novel situations and discussion of its trade-offs.

PATTERNS:

PATTERNS Patterns are derived for both analysis and design phase of software development Analysis patterns capture conceptual models in application domain. Design patterns focus on organizational acceptance and usability of the final systems. The benefits and drawbacks of patterns are as follows :

PATTERNS:

PATTERNS A pattern is an idea that has been useful in one practical context and will probably be useful in others - Martin Fowler A pattern is a three-part rule, which expresses a relation between a certain context, a problem, and a solution - Christopher Alexander

PATTERNS:

PATTERNS Patterns : – Are not invented. They are harvested from existing solutions . – Are given a name to aid in communications. – Are documented in a rigorous fashion Sometimes conflict with each other. For example: you apply a patterns to solve one problem, but by doing so, you may introduce others. – This is called a contradiction, or side-effect. – These are the tradeoffs designers have to deal with!

Design Pattern Advantages:

Design Pattern Advantages Using patterns offers a few key advantages: Leverage a proven solution Provide a common vocabulary

Leverage a Proven Solution:

Leverage a Proven Solution The solution for a pattern has been designed, implemented and tested Reusing these solutions allows most of each of these steps to be eliminated If the implementation of a pattern is used, the design, implementation, and testing are minimal just to ensure the proper behaviour exists If the design of a pattern is used, the solution specific to the problem must be implemented and tested, but need not be redesigned

Provide a Common Vocabulary:

Provide a Common Vocabulary Some patterns are very common Documenting and cataloguing patterns allows designers and architects to describe a solution using patterns as part of the language Typically, this can make descriptions of solutions shorter Architects and designers can more easily communicate their designs to their developers

PATTERNS:

PATTERNS Benefits Drawbacks Increase Developer Productivity Insist the developer Promote reuse of development efforts NIH(Not-invented-here) syndrome can get in the way Describe proven solutions to common problems Many developers are not willing to accept the work of others Increase the consistency between applications It is very hard to accept to reuse the ideas, since each problem is unique Potentially better than reusable code since the system platforms make the reusable code difficult to use Pattern is quickly becoming a buzzword by marketing people rather than its intend

Design Patterns:

Design Patterns Design patterns are partial solutions to common problems , such as separating an interface from a number of alternate implementations, wrapping around a set of exiting classes. Design patterns are devices that allow systems to share knowledge about their design, by describing commonly recurring structures of communicating components that solve a general design problem within a particular context.

Gang of Four :

Gang of Four Pattern-based design was introduced into architecture and engineering in the 1950's Almost immediately, software engineers began using patterns for designing software It wasn't until a group of four researchers combined forces that pattern-based design became well-known and commonplace This group was known as the gang of four ( GoF )

Gang of Four :

Gang of Four The gang of four ( GoF ) is: Erich Gamma Richard Helm Ralph Johnson John Vlissides They are the authors of the famous text "Design Patterns: Elements of Reusable Object-Oriented Software"

GRASP Patterns:

GRASP Patterns GRASP: G eneralized R esponsibility A ssignment S oftware P atterns These are not design patterns , rather fundamental principles of object design GRASP patterns focus on one of the most important aspects of object design assigning responsibilities to classes . GRASP patterns do not address architectural design

What is object design:

What is object design A simple definition In the analysis part of the current and previous iterations you have - Identified use cases and created use case descriptions to get the requirements - Created and refined the domain concept model

What is object design:

What is object design In order to make a piece of object design Assign methods to software classes Design how the classes collaborate (i.e. send messages ) in order to fulfill the functionality stated in the use cases.

A critical step in object design:

A critical step in object design Central tasks in design are: - Deciding what methods belong where - How the objects should interact A use-case realization describes how a particular use case is realized within the design model in terms of collaborating objects . .

A critical step in object design:

A critical step in object design Use-case realization work is a design activity, the design grows with every new use case realization Interaction diagrams and patterns apply while doing use-case realizations

Granularity of a responsibility:

Granularity of a responsibility The translation of problem domain responsibilities into classes and methods is influenced by the granularity of the responsibility . A responsibility is not the same thing as a method, but methods are implemented to fulfill responsibilities

What are responsibilities:

What are responsibilities Responsibilities are related to the problem domain In design model, responsibilities are obligations of an object in terms of its behavior. There are two main types of responsibilities : Doing Knowing

Doing responsibilities::

Doing responsibilities : Doing something itself such as creating an object or doing a calculation Initiating action in other objects Controlling and coordinating activities in other objects.

Knowing responsibilities:

Knowing responsibilities Knowing about private encapsulated data Knowing about related objects. Knowing about things it can derive or calculate . Knowing are often easy to infer from the domain model, where the attributes and associations are illustrated

Granularity of a responsibility:

Granularity of a responsibility Example The Sale class might define a methods to know its total; say, a method named getTotal . The Sale may collaborate with other objects, such as sending a getSubtotal message to each SalesLineltem object asking for its subtotal.

GRASP – learning and doing Basic Design:

GRASP – learning and doing Basic Design The GRASP patterns are a learning aid to help one understand essential object design . Design reasoning is applied in a methodical , rational , explainable way. GRASP approach is based on assigning responsibilities , thus creating the basic object and control structures - Guided by patterns of assigning responsibilities.

Responsibilities and Interaction Diagrams:

Responsibilities and Interaction Diagrams Responsibilities are assigned to objects during object design while creating interaction diagrams. - Sequence diagrams - Collaboration diagrams Examples: " a Sale is responsible for creating SalesLineltems " (a doing), or " a Sale is responsible for knowing its total " (a knowing).

:

Responsibilities and methods :Sale :Payment makePayment create makePayment implies Sale object has a responsibility to create a Payment object

:

Responsibilities and Interaction Diagrams Interaction diagrams show choices in assigning responsibilities to objects. GRASP patterns guide choices in where to assign responsibilities. GRASP patterns are a codification of widely used basic principles.

Assignment of Responsibilities:

Assignment of Responsibilities . A responsibility is: Related to the methods and data of classes. Fulfilled with one or more methods. Possibly spread across classes.

Responsibility Assignment is the Key:

Responsibility Assignment is the Key Appropriate assignment of responsibilities to classes is the key to successful design. There are fundamental principles in assigning responsibilities that experienced designers apply. These principles are summarized in the GRASP patterns

The GRASP Patterns:

The GRASP Patterns Memorization and application of these patterns are critical for successful object-oriented designs. 1 . Information Expert . 2. Creator. 3. Controller. 4. Low Coupling. 5. High Cohesion. 6. Polymorphism. 7. Pure Fabrication. 8. Indirection. 9. Don’t Talk to Strangers.

Information Expert:

Solution Assign a responsibility ( such as behaviour) to the information expert — the class with the information necessary to fulfill the responsibility . e.g. A responsibility such as handling a deposit (i.e. increase balance) should be assigned to the Account class ( This is because Account contains the account balance as one of its attributes) Information Expert

Information Expert:

Information Expert Problem What is a general principle of assigning responsibilities to objects? Who should be responsible for knowing/doing …? Domain model (domain expert, domain analysis) to design model (software classes). Any existing to any representative Answer: 1. If there are relevant classes in the Design Model, look there first. 2. Else, look in the Domain Model, and attempt to use (or expand) its representations to inspire the creation of corresponding design classes.

Example: What information is needed to determine the grand total? :

Example : What information is needed to determine the grand total? Look to the Domain Model for information experts; perhaps the real-world Sale is one Add a software class to the Design Model similarly called Sale, and give it the responsibility of knowing its total , expressed with the method named getTotal . This approach supports low representational gap( concepts of how the real domain is organized .)

:

Consider the partial Domain Model What information is needed to determine the grand total ? It is necessary to know about all the SalesLineltem instances of a sale and the sum of their subtotals . Example: What information is needed to determine the grand total? Sale date Product description price itemID

Continues…:

Continues… A Sale instance contains these; therefore, by the guideline of Information Expert, Sale is a suitable class of object for this responsibility; it is an information expert for the work

PowerPoint Presentation:

Sale date Product description price itemID SalesLineItem quantity Who is information expert ? Sale

PowerPoint Presentation:

Sale date Product description price itemID SalesLineItem quantity getTotal getSubTotal getPrice

PowerPoint Presentation:

Information Expert is frequently used in the assignment of responsibilities; it is a basic guiding principle used continuously in object design I t expresses the common "intuition" that objects do things related to the information they have. Design Class Responsibility Sale knows sale total SalesLineltem knows line item subtotal ProductSpecification knows product price

Example:

Example

Continues - Expert:

Continues - Expert Contraindications There are situations where a solution suggested by Expert is undesirable, usually because of problems in coupling and cohesion - who should be responsible for saving a Sale in a database ? Benefits Information encapsulation is maintained, since objects use their own information to fulfill tasks Behavior is distributed across the classes that have the required information

Continues - Expert:

Continues - Expert Related Patterns or Principles Low Coupling High Cohesion Also Known As; Similar To "Place responsibilities with data" " That which knows, does“ "Do It Myself“ "Put Services with the Attributes They Work On."

CREATOR:

CREATOR Solution Assign class B the responsibility to create an instance of class A if one or more of the following is true: 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 (thus B is an Expert with respect to creating A). B is a creator of A objects. If more than one option applies, prefer a class B which aggregates or contains class A.

CREATOR:

CREATOR e.g. Consider an Invoice which has a number of InvoiceItems on it When a new Invoice is created, we might wish to add new items to it It makes sense that the Invoice itself would create instances of InvoiceItem , and subsequently add them to itself The effect is that no other classes should need to know about InvoiceItems (at least not for this responsibility)

CREATOR:

CREATOR Who should create an instance of a particular class? Consider assigning Class B the responsibility to create an instance of class A if one of the following is true: B contains A. B aggregates A. B records A. B closely uses A. B is the “creator” of A instances. This pattern supports low coupling.

CREATOR:

CREATOR

CREATOR:

CREATOR Problem Who should be responsible for creating a new instance of some class? Creational Design Pattern The creation of objects is one of the most common activities in an object-oriented system . Consequently, it is useful to have a general principle for the assignment of creation responsibilities. Assigned well, the design can support low coupling , increased clarity, encapsulation, and reusability

EXAMPLE - CREATOR:

EXAMPLE - CREATOR who should be responsible for creating a SalesLineltem instance ? By Creator, we should look for a class that aggregates, contains, and so on , SalesLineltem instances . Consider the partial domain model

PowerPoint Presentation:

Sale date Product description price itemID SalesLineItem quantity Who is creator ? SalesLineltem

CREATOR:

CREATOR Since a Sale contains (in fact, aggregates) many SalesLineltem objects, the Creator pattern suggests that Sale is a good candidate to have the responsibility of creating SalesLineltem instances This assignment of responsibilities requires that a makeLineltem method be defined in Sale

CREATOR:

CREATOR Creator guides assigning responsibilities related to the creation of objects, a very common task. The basic intent of the Creator pattern is to find a creator that needs to be connected to the created object in any event. Choosing it as the creator supports low coupling. Aggregate aggregates Part, Container contains Content, and Recorder records Recorded are all very common relationships between classes in a class diagram.

CREATOR:

CREATOR Creator suggests that the enclosing container or recorder class is a good candidate for the responsibility of creating the thing contained or recorded. Of course , this is only a guideline . T he concept of aggregation has been used in considering the Creator pattern For example , assume that a Payment instance needs to be initialized, when created , with the Sale total. Since Sale knows the total, Sale is a candidate creator of the Payment .

CREATOR:

CREATOR Contraindications creation requires significant complexity, such as using recycled instances for performance reasons, conditionally creating an instance from one of a family of similar classes based upon some external property value, and so forth Benefits Low coupling is supported, which implies lower maintenance dependencies and higher o pportunities for reuse .

CREATOR:

CREATOR Related Patterns or Principles Low Coupling Factory Whole-Part describes a pattern to define aggregate objects that support encapsulation of components

Low Coupling:

Low Coupling Coupling is a measure of how strongly one element is connected to, has knowledge of, or relies on other elements. An element with low (or weak) coupling is not dependent on too many other These elements include classes, subsystems, systems, and so on . Solution Assign a responsibility so that coupling remains low . Problem How to support low dependency, low change impact, and increased reuse?

Low Coupling:

Low Coupling A class with high (or strong) coupling relies on many other classes. Such classes may be undesirable; some suffer from the following problems: Changes in related classes force local changes. Harder to understand in isolation. Harder to reuse because its use requires the additional presence of the classes on which it is dependent . Example Payment, register, and sale.

Low Coupling :

Low Coupling Assume we have a need to create a Payment instance and associate it with the Sale . What class should be responsible for this? Since a Register "records" a Payment in the real-world domain, the Creator pattern suggests Register as a candidate for creating the Payment. The Register instance could then send an addPayment message to the Sale, passing along the new Payment as a parameter

Low Coupling:

Low Coupling Design I Design II This assignment of responsibilities couples the Register class to knowledge of the Payment class :Sale :Payment :Register create addPayment makePayment :Payment :Sale :Register makePayment create makePayment

Low Coupling:

Low Coupling Which design, based on assignment of responsibilities , supports Low Coupling? In both cases we will assume the Sale must eventually be coupled to knowledge of a Payment. Design 1, in which the Register creates the Payment, adds coupling of Register to Payment, while Design 2, in which the Sale does the creation of a Payment , does not increase the coupling Purely from the point of view of coupling , Design Two is preferable because overall lower coupling is maintained.

Low Coupling:

Low Coupling Low Coupling is a principle to keep in mind during all design decisions; it is an underlying goal to continually consider. It is an evaluative principle that a designer applies while evaluating all design decisions . Low Coupling encourages assigning a responsibility so that its placement does not increase the coupling to such a level that it leads to the negative results that high coupling can produce.

Low Coupling:

Low Coupling Low Coupling supports the design of classes that are more independent, which reduces the impact of change . A subclass is strongly coupled to its superclass There is no absolute measure of when coupling is too high The extreme case of Low Coupling is when there is no coupling between classes. This is not desirable because a central metaphor of object technology is a system of connected objects that communicate via messages.

:

Contraindications High coupling to stable elements and to pervasive elements is seldom a problem For example, a Java J2EE application can safely couple itself to the Java libraries ( java.util , and so on), because they are stable and widespread . Benefits not affected by changes in other components simple to understand in isolation convenient to reuse

Low Coupling:

Low Coupling Coupling and cohesion are truly fundamental principles in design , and should be appreciated and applied as such by all software developers. A good rule of thumb is: If class A is already coupled with class B, assign a responsibility for B to the class A Related Patterns Protected Variation

Low Coupling:

Low Coupling The reasons why Low Coupling is important should be obvious: With Low Coupling, changes to a class (A) affect fewer classes (the classes coupled to A) Thus Low Coupling improves the maintainability of a software system A low coupled class is also easy to understand, since it is often simpler and more cohesive

High Cohesion:

High Cohesion Solution Assign a responsibility so that cohesion remains high . Problem How to keep complexity manageable ? Cohesion ( functional cohesion) is a measure of how strongly related and focused the responsibilities of an element are . An element with highly related responsibilities, and which does not do a tremendous amount of work, has high cohesion. These elements include classes , subsystems , and so on.

High Cohesion:

High Cohesion A class with low cohesion does many unrelated things, or does too much work . Such classes are undesirable; they suffer from the following problems: hard to comprehend hard to reuse hard to maintain delicate; constantly effected by change Low cohesion classes often represent a very "large grain" of abstraction, or have taken on responsibilities that should have been delegated to other objects.

High Cohesion :

High Cohesion Example The same example problem used in the Low Coupling pattern can be analyzed for High Cohesion . Assume we have a need to create a (cash) Payment instance and associate it with the Sale. What class should be responsible for this? Since Register records a Payment in the real-world domain, the Creator pattern suggests Register as a candidate for creating the Payment. The Register instance could then send an addPayment message to the Sale, passing along the new Payment as a parameter,

High Cohesion:

High Cohesion Design I – Register creates Payment Design II – Sale creates Payment :Sale :Payment :Register create addPayment makePayment :Payment :Sale :Register makePayment create makePayment

High Cohesion :

High Cohesion This assignment of responsibilities places the responsibility for making a payment in the Register. The Register is taking on part of the responsibility for fulfilling the makePayment system operation . but if we continue to make the Register class responsible for doing some or most of the work related to more and more system operations, it will become increasingly burdened with tasks and become incohesive

High Cohesion :

High Cohesion The second design delegates the payment creation responsibility to the Sale, which supports higher cohesion Since the second design supports both high cohesion and low coupling, it is desirable .

High Cohesion:

High Cohesion Like Low Coupling, High Cohesion is a principle to keep in mind during all design decisions; it is an underlying goal to continually consider. It is an evaluative principle that a designer applies while evaluating all design decisions . Grady Booch describes high functional cohesion - "all work together to provide some well-bounded behavior "

High Cohesion:

High Cohesion Varying degrees of functional cohesion Very low cohesion - A class is solely responsible for many things in very different functional areas . Low cohesion - A class has sole responsibility for a complex task in one functional area . High cohesion- A class has moderate responsibilities in one functional area and collaborates with other classes to fulfill tasks .

:

Moderate cohesion - A class has lightweight and sole responsibilities in a few different areas that are logically related to the class concept, but not to each other As a rule of thumb, a class with high cohesion has a relatively small number of methods , with highly related functionality, and does not do too much work. It collaborates with other objects to share the effort if the task is large.

High Cohesion :

High Cohesion A class with high cohesion is advantageous because it is relatively easy to maintain , understand , and reuse. The high degree of related functionality, combined with a small number of operations, also simplifies maintenance and enhancements. The fine grain of highly related functionality also supports increased reuse potential

High Cohesion :

High Cohesion The High Cohesion pattern has a real-world analogy. It is a common observation that if a person takes on too many unrelated responsibilities . especially ones that should properly be delegated to others then the person is not effective These people suffer from low cohesion

High Cohesion :

High Cohesion Another Classic Principle: Modular Design Coupling and cohesion are old principles in software design; designing with objects does not imply ignoring well-established fundamentals. Another of these which is strongly related to coupling and cohesion is to promote modular design. Modularity is the property of a system that has been decomposed into a set of cohesive and loosely coupled modules

High Cohesion:

High Cohesion We promote a modular design by creating methods and classes with high cohesion. At the basic object level, modularity is achieved by designing each method with a clear, single purpose, and grouping a related set of concerns into a class. Contraindications There are a few cases in which accepting lower cohesion is justified.

High Cohesion :

High Cohesion One case is the grouping of responsibilities or code into one class or component to simplify maintenance by one person although be warned that such grouping may also make maintenance worse - embedded SQL statements - distributed across ten classes - it is common that only one or two SQL experts know how to best define and maintain this SQL – more number of experts in a team - The software architect may decide to group all the SQL statements into one class, RDBOperations , so that it is easy for the SQL expert to work on the SQL in one location

High Cohesion:

High Cohesion Another case for components with lower cohesion is with distributed server objects. Because of overhead and performance implications associated with remote objects and remote communication, it is sometimes desirable to create fewer and larger, less cohesive server objects that provide an interface for many operations . This is also related to the pattern called Coarse-Grained Remote Interface , in which the remote operations are made more coarse-grained in order to do or request more work in remote operation call, because of the performance penalty of remote calls over a network

High Cohesion:

High Cohesion Benefits Clarity and ease of comprehension of the design is increased. Maintenance and enhancements are simplified. Low coupling is often supported. The fine grain of highly related functionality supports increased reuse because a cohesive class can be used for a very specific purpose

Cohesion and Coupling :

Cohesion and Coupling Cohesion and Coupling are two of the most important concepts in software design However, they are not completely unrelated: Highly coupled classes often are not cohesive A class that has been assigned many responsibilities for many external classes is unlikely to represent a single abstraction

Controller:

Controller Problem Who should be responsible for handling an input system event? An input system event is an event generated by an external actor. They are associated with system operations - operations of the system in response to system events, just as messages and methods are related. For example, when a cashier using a POS terminal presses the "End Sale" button , he is generating a system event indicating "the sale has ended." Similarly , when a writer using a word processor presses the "spell check" button, he is generating a system event indicating "perform a spell check."

Controller …,:

Controller …, A Controller is a non-user interface object responsible for receiving or handling a system event. A Controller defines the method for the system operation Solution Assign the responsibility for receiving or handling a system event message to a class representing one of the following choices: Represents the overall system, device, or subsystem (facade controller , Jukebox)

Controller …,:

Controller …, Represents a use case scenario within which the system event occurs, often named < UseCaseName >Handler ,< UseCaseName >Coordinator , or<Use- CaseName >Session( use-case or session controller ). Example:makeSaleHandler , makeSaleCoordinator , etc. Use the same controller class for all system events in the same use case scenario. Informally , a session is an instance of a conversation with an actor.

Controller …,:

Controller …, Sessions can be of any length, but are often organized in terms of use cases (use case sessions ). "window," "applet," "widget," "view," and "document" classes are not on this list. Such classes should not fulfill the tasks associated with system events, they typically receive these events and delegate them to a controller . A Controller is never a user interface object

Controller ..,:

Controller .., The decision to create system controllers vs. use case controllers are often driven by the dynamics of high cohesion vs. low coupling. This GRASP is just common sense: When a system event occurs, the class who has the responsibility of performing a high level function should receive events indicating it should take place Often a subsystem will have one or more Controller classes, each designed to handle certain responsibilities Controller responsibilities are usually extremely high-level

Controller…,:

Controller…, Assign the responsibility for handling a system operation message to one of these options: The business or overall organization (a façade controller). The overall “system” (a façade controller). An animate thing in the domain that would perform the work (a role controller). An artificial class representing the use case (a use-case controller).

:

Example In a bank system, we might have a Controller that manages all banking transactions ( TransactionController ) This class would have methods such as: deposit() withdraw() payBill () transfer() It makes sense that this class receive the event generated when the teller clicks the ‘Execute Bill Payment’ button on the user interface 5. Controller

Controller - Facades :

Controller - Facades Facades are “covers.” Intent - A class that (in some way) represents an overall cover. Many possibilities. Example: The entire organization.

Controller - Facades :

Controller - Facades Other facades? A class representing the “system.” Examples: The software information system. The device that includes a computer and software such as an ATM. Others.

Controller:

Controller

Controller :

Controller Systems receive external input events, typically involving a GUI operated by a person . Other mediums of input include external messages such as in a call processing telecommunications switch, or signals from sensors such as in process control systems. In all cases, if an object design is used, some handler for these events must be chosen . The Controller pattern provides guidance for generally accepted, suitable choices . the controller is a kind of facade into the domain layer from the interface layer .

Controller:

Controller It is often desirable to use the same controller class for all the system events of one use case so that it is possible to maintain information about the state of the use case in the controller. Such information is useful, for example, to identify out-of-sequence system events (for example, a makePayment operation before an endSale operation). Different controllers may be used for different use cases. A common defect in the design of controllers is to give them too much responsibility.

Controller:

Controller Benefits Increased potential for reuse, and pluggable interfaces An interface-as-controller design reduces the opportunity to reuse logic in future applications, since it is bound to a particular interface Reason about the state of the use case It is necessary to ensure that system operations occur in a legal sequence, or to be able to reason about the current state of activity and operations within the use case that is underway

Bloated Controllers:

Bloated Controllers Issues and Solutions Poorly designed, a controller class will have low cohesion . unfocused and handling too many areas of responsibility; this is called a bloated controller. Signs of bloating include: There is only a single controller class receiving all system events in the system , and there are many of them. This sometimes happens if a facade controller is chosen. The controller itself performs many of the tasks necessary to fulfill the system event, without delegating the work. This usually involves a violation of Information Expert and High Cohesion.

Bloated Controllers…,:

Bloated Controllers…, A controller has many attributes, and maintains significant information about the system or domain, which should have been distributed to other objects , or duplicates information found elsewhere There are several cures to a bloated controller, including: 1 . Add more controllers - a system does not have to have only one. Instead of facade controllers, use use-case controllers. .

Bloated Controllers…,:

Bloated Controllers…, For example, consider an application with many system events, such as an airline reservation system Use-case controllers MakeReservationHandler ManageSchedulesHandler ManageFaresHandler 2. Design the controller so that it primarily delegates the fulfillment of each system operation responsibility on to other objects

Related Patterns - Controller:

Related Patterns - Controller Command —In a message-handling system, each message may be represented and handled by a separate Command object Facade —A facade controller is a kind of Facade. Layers —This is a POSA pattern]. Placing domain logic in the domain layer rather than the presentation layer is part of the Layers pattern.

Pure Fabrication:

Pure Fabrication This is another GRASP pattern . A Pure Fabrication is an arbitrary creation of the designer, not a software class whose name is inspired by the Domain Model. A use-case controller is a kind of Pure Fabrication .

Pure Fabrication:

Pure Fabrication To support high cohesion and low coupling, where no appropriate class is present: invent one Even if the class does not represent a problem domain concept This is a compromise that often has to be made to preserve cohesion and low coupling Remember: the software is not designed to simulate the domain, but operate in it The software does not always have to be identical to the real world

Pure Fabrication:

Pure Fabrication Pure Fabrication is a compromise when faced with a choice between modeling the domain and preserving maintainability and class reusability Software maintainability and reuse are always more important in business, since they are ways companies can preserve resources Usually, Pure Fabrication is used when there is no appropriate class to use Usually, it is a good idea to try the other patterns first to try to find a solution which more closely resembles the domain entities

Pure Fabrication:

Pure Fabrication It was suggested that entities in a UML editor draw themselves However, what if this is a difficult task? What if the drawing facilities vary depending on what drawing facilities the user has installed? e.g. DirectX, OpenGL, etc. The real world suggests that the Architect class draw the entities This is because architects draw UML diagrams

Pure Fabrication:

Pure Fabrication Architect might be used to store user preferences, recently created diagrams and projects, etc. This would obviously be a cohesion problem Pure Fabrication would suggest creating a class whose job is to draw the entities One solution might be to have the Entity instances associate with an instance of EntityRenderer component There could be a subclass of EntityRenderer for each subclass of Entity e.g. UseCaseRenderer , ActorRenderer

Pure Fabrication:

Pure Fabrication The difficulty then becomes: how do we associate the entity instances with the right instance of renderer? This is a problem easily solved by the AbstractFactory pattern, discussed later

Polymorphism:

Polymorphism When related behaviours vary by type (class), assign the responsibility polymorphically to the specialization classes This is basically the purpose of polymorphism, so it is natural for software developers to understand This is not much of a pattern, and yet another best practice

Polymorphism:

Polymorphism e.g. Consider a UML diagram drawing program If shapes are responsible for drawing themselves via the draw() method: Obviously, an Actor (stick figure) will draw itself differently than a UseCase (ellipse) It might make sense in this case to have the classes themselves handle the drawing by polymorphically overriding the draw() method An advantage is that new entities (e.g. State) can be easily added without changing the core graphics code

Polymorphism:

Polymorphism Polymorphism can lead to highly cohesive objects Consider the example where some draw() method were implemented similarly to this: If ( entity.type = “ UseCase ”) then drawEllipse (…); Else if ( entity.type = “Class”) then drawRectangle (…); … End if This is not highly cohesive, since it combines unrelated behaviours, and it also strongly couples this object with the shape it draws

Indirection:

Indirection To avoid direct coupling between objects, assign an intermediate object as a mediator Recall that coupling between two classes of different subsystems can introduce maintenance problems Another possibility is that two classes would be otherwise reusable (in other contexts) except that one has to know of the other Coupling the two objects would reduce the reuse contexts to where both abstract concepts were relevant together The objects could not be reused separately

Indirection:

Indirection e.g. Consider an application for managing group work Employee instances might need to be coupled to Project instances However, potential for reuse of both Employee and Project is high One solution is to assign a class (Assignment) to couple the two classes In this case, the class represents an association class (a class that represents an association)

Indirection:

Indirection The Façade pattern is another example of Indirection The Façade prevents coupling classes in two different subsystems Classes in one subsystem communicate directly with the Façade The Façade communicates with the correct subsystem component Thus, changes to the structure of the subsystem will not affect the user of the subsystem, thanks to the Façade

Protected Variations:

Protected Variations Assign responsibility to create a stable interface around an unstable or predictably variable subsystem or component If a component changes frequently, the users of the component will also have to be modified This is especially time consuming if the component has many users Wrapping the component in a stable interface means that when variations occur, the wrapper class need only be changed In other words, changes are localized

Protected Variations:

Protected Variations e.g. Big video game companies make money by creating a 3D graphics game engine (as well as sound, AI, etc.) These video game companies often produce many games using the same engine, and release the game on many consoles This is only possible to this extent using Protected Variations If a game is to be ported to another console, the wrapper object will have to delegate 3D graphics drawing to different console-level commands However, the wrapper is simpler to change than the entire game and all of its facets

Protected Variations:

Protected Variations These video game companies facilitate additional revenue by making their wrapper modules flexible, so that they can create many games using the same interface Thus, a good practice is to leave out unnecessary details in wrappers It is often useful to try to preserve the cohesion (and thus reuse factor) of a subsystem by keeping the interface flexible Obviously, the Façade pattern is also an example of Protected Variations

Protected Variations:

Protected Variations One popular pattern using Protected Variations is the Adapter An Adapter is another pattern, discussed later, which adapts one interface for another Perhaps an application (e.g. a game) is written to use a one interface (e.g. OpenGL for 3D graphics) The application (game) might need to be adapted to also run on other platforms (e.g. DirectX/Direct3D) An Adapter is intended for this kind of application An OpenGL-to-Direct3D adapter is possible

Protected Variations:

Protected Variations Among other examples are JDBC and ODBC: These are packages that allow applications to access databases in a DB-independent way In spite of the fact that databases all use slightly different methods of communication It is possible due to an implementation of Protected Variations Users write code to use a generic interface An adapter converts the generic method calls to DB-specific communications and vice versa

Don’t Talk to Strangers:

Don’t Talk to Strangers Do not couple two objects who have no obvious need to communicate This is common sense: do not add coupling where unnecessary Again, this is a best practice in software Although common sense, this still must be considered seriously, as a tendency exists to model all possible relationships

Don’t Talk to Strangers:

Don’t Talk to Strangers Often the domain objects have relationships that need not be modeled in the application However, a common tendency is to model those relationships (with aggregation, for instance) anyway Model relationships only if they are necessary to complete a use case Ultimately it is not relationships in the domain that determine if relationships in software should be present

PowerPoint Presentation:

e.g. Consider a convenience store application Customers are people, as are Employees Should we model this as inheritance? In this application, customers are likely anonymous Thus, Employee instances (which likely store names and phone numbers) do not share any common data or behaviour It makes sense that we not model this relationship, despite our initial reactions

authorStream Live Help