Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to...

28
Design Patterns Part two Part two

Transcript of Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to...

Page 1: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

Design Patterns

Part twoPart two

Page 2: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

Structural Patterns

Concerned with how classes and objects are Concerned with how classes and objects are composed to form larger structures composed to form larger structures

Structural Structural classclass patterns – use inheritance to patterns – use inheritance to compose interfaces or implementations. compose interfaces or implementations.

Structural Structural objectobject patterns – describe ways to patterns – describe ways to compose objects creating new functionality. compose objects creating new functionality.

Page 3: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

The Façade Pattern

Provides a single interface into a subsystem.Provides a single interface into a subsystem.

Used to separate or simplify the subsystem Used to separate or simplify the subsystem in the program.in the program.

Used in UIs to separate a GUI from the Used in UIs to separate a GUI from the underlying ‘business logic’underlying ‘business logic’

Page 4: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

Façade – Use When:

A simple interface into a complex subsystem is A simple interface into a complex subsystem is required.required.

A subsystem’s details are not or should not be A subsystem’s details are not or should not be required knowledge for other componentsrequired knowledge for other components..

Subsystems should be compartmentalized, Subsystems should be compartmentalized, decoupling the system from the ‘black box’. This decoupling the system from the ‘black box’. This allows for easier changes within the isolated allows for easier changes within the isolated subsystem, as long as the API for the system isn’t subsystem, as long as the API for the system isn’t alteredaltered

Layering of subsystems is requiredLayering of subsystems is required

Page 5: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

Façade - Benefits Shields clients from subsystem components.Shields clients from subsystem components.

Promotes a weak coupling between subsystems, Promotes a weak coupling between subsystems, allows subsystem change without affecting clients.allows subsystem change without affecting clients.

This pattern helps simplify complex or circular This pattern helps simplify complex or circular subsystems for outside users.subsystems for outside users.

Possible compile time reduction, as not all Possible compile time reduction, as not all components may need to be recompiled.components may need to be recompiled.

Page 6: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

Façade – Example

You want to make a platform-independent front You want to make a platform-independent front end to a databaseend to a database Database runs on any target systemDatabase runs on any target system Front end is (almost always) platform Front end is (almost always) platform

dependentdependent Create a façade API to program the GUI toCreate a façade API to program the GUI to

Moving to a new platform means Moving to a new platform means reimplementing the GUI, but not the API or the reimplementing the GUI, but not the API or the back end codeback end code

Page 7: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

Implementation Points

Subsystem coupling can be reduced if the façade is Subsystem coupling can be reduced if the façade is an abstract class, and concrete classes implement an abstract class, and concrete classes implement the subsystem itself. This prevents clients from the subsystem itself. This prevents clients from knowing details about which subsystem is used.knowing details about which subsystem is used. Also, consider the use of interfaces in JavaAlso, consider the use of interfaces in Java

Judicious use of public and private classes and Judicious use of public and private classes and methods can help provide subsystem independence methods can help provide subsystem independence and encapsulation. (Consider the use of package and encapsulation. (Consider the use of package security in Java)security in Java)

Page 8: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

The Proxy Pattern

The Proxy provides a surrogate or placeholder, The Proxy provides a surrogate or placeholder, often to control access to it.often to control access to it.

There are four general categories of proxy.There are four general categories of proxy.

Used when there needs to be a more versatile Used when there needs to be a more versatile reference to an object, or when it is not practical reference to an object, or when it is not practical or desired to reference the original.or desired to reference the original. Example: large image that eats a lot of memoryExample: large image that eats a lot of memory

Page 9: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

Proxy Categories Remote Proxy: Local representative for objects in Remote Proxy: Local representative for objects in

different spaces.different spaces.

Virtual Proxy: Creates expensive objects on Virtual Proxy: Creates expensive objects on demand.demand.

Protection Proxy: Controls access, can be similar Protection Proxy: Controls access, can be similar to a Façade.to a Façade.

Smart Reference: Various value adds, such as Smart Reference: Various value adds, such as object loading, tracking instances, object or object loading, tracking instances, object or database locking.database locking.

Page 10: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

Proxy Benefits

Remote proxy can hide resident details.Remote proxy can hide resident details.

Virtual proxy creates expensive objects on Virtual proxy creates expensive objects on demand, rather than all at startup.demand, rather than all at startup. Example: dialog boxesExample: dialog boxes

Protection and Smart Proxies can allow Protection and Smart Proxies can allow housekeeping an other tasks to be encapsulated.housekeeping an other tasks to be encapsulated.

Page 11: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

Proxy – Example

Your program must be ready to display a Your program must be ready to display a large number of graphical images, but not large number of graphical images, but not all of them can be seen by the user at one all of them can be seen by the user at one time. A virtual proxy could be used to load time. A virtual proxy could be used to load the image only when needed by the user, so the image only when needed by the user, so that the time to open the application is not that the time to open the application is not slowed by image loading. slowed by image loading.

Page 12: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

Behavioral Patterns Concerned with algorithms and the assignment of Concerned with algorithms and the assignment of

object responsibilitiesobject responsibilities.. Describe not just the patterns of objects but how Describe not just the patterns of objects but how

they communicate.they communicate. Behavioral class patterns use inheritance to Behavioral class patterns use inheritance to

distribute behavior to classes.distribute behavior to classes. Behavioral object patterns use object composition Behavioral object patterns use object composition

rather than inheritance. Often, this describe how a rather than inheritance. Often, this describe how a group of objects cooperate to perform a task and group of objects cooperate to perform a task and what objects need to know about which others.what objects need to know about which others.

Page 13: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

The Command Pattern

Encapsulates a request as an object.Encapsulates a request as an object.

Page 14: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

Command – Use When:

Useful to issue requests without knowing details Useful to issue requests without knowing details about the operation or recipient.about the operation or recipient.

Objects can be parameterized by an action to Objects can be parameterized by an action to perform.perform.

A framework executes a generic command, and A framework executes a generic command, and the command object is extended to do the the command object is extended to do the application specific method.application specific method.

Page 15: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

Command Benefits

Command allows the calling object to be separate Command allows the calling object to be separate from the one that can perform it.from the one that can perform it.

Commands can be assembled together to form Commands can be assembled together to form more complex commands. An example of this is more complex commands. An example of this is the MacroCommand, which will not be discussed the MacroCommand, which will not be discussed here.here.

Adding new commands is easy, and existing Adding new commands is easy, and existing classes won’t have to change.classes won’t have to change.

Page 16: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

Command - Benefits

Support can be added for operations undo Support can be added for operations undo and redo.and redo.

Security can be enhanced by logging user Security can be enhanced by logging user actions through centralized Command actions through centralized Command objects.objects.

Page 17: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

Command – Example

The application you are working on must The application you are working on must support a log of all user activity for security support a log of all user activity for security purposes. To do this, you use a central purposes. To do this, you use a central command object which will be able to command object which will be able to determine what actions a user has taken and determine what actions a user has taken and can then log them or do whatever actions can then log them or do whatever actions are required.are required.

Page 18: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

Implementation Points

Consider command object intelligence. It can be a Consider command object intelligence. It can be a simple object between a requestor and a recipient. simple object between a requestor and a recipient.

For undo/redo, consider what parameters and For undo/redo, consider what parameters and information must be stored.information must be stored.

If using C++, templates may be used if commands If using C++, templates may be used if commands aren’t undoable and don’t require arguments.aren’t undoable and don’t require arguments. Try to limit the number of undoable commands; it bug Try to limit the number of undoable commands; it bug

the user….the user….

Page 19: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

The Observer Pattern

Defines a one-to-many dependency or Defines a one-to-many dependency or communication flow between objects. When one communication flow between objects. When one object is updated, all dependents are notified object is updated, all dependents are notified automatically. automatically.

This is one of the most important patterns in GUI This is one of the most important patterns in GUI development, as it abstracts the notion of the development, as it abstracts the notion of the “callback”“callback” Some event occurs (user clicks a button) and Some event occurs (user clicks a button) and

something else is notified (function is called)something else is notified (function is called)

Page 20: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

Observer – Use When:

An abstraction has two aspects, one dependent on An abstraction has two aspects, one dependent on the other. Encapsulating these pieces in separate the other. Encapsulating these pieces in separate objects lets you vary and reuse them objects lets you vary and reuse them independently.independently.

A change to one object requires changing others; A change to one object requires changing others; the number to be changed may be dynamic or the number to be changed may be dynamic or unknown.unknown.

An object should be able to notify others without An object should be able to notify others without making assumptions about what the objects are. making assumptions about what the objects are.

Page 21: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

Observer - Benefits Abstracts the coupling between the notifying object Abstracts the coupling between the notifying object

and observers. All the notifying object knows is it and observers. All the notifying object knows is it has a group of observing objects to send a message to. has a group of observing objects to send a message to.

Good object oriented programming, where a message Good object oriented programming, where a message is sent, but each object’s action is independent.is sent, but each object’s action is independent.

Support for broadcast communication. Objects can Support for broadcast communication. Objects can register or deregister as needed, and the notifying register or deregister as needed, and the notifying object only has to know which objects currently need object only has to know which objects currently need notification.notification.

Page 22: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

Observer - Drawbacks

Care must be taken to ensure that messages Care must be taken to ensure that messages sent to observers don’t themselves trigger sent to observers don’t themselves trigger more messages to be sent, causing an more messages to be sent, causing an operation to become an infinite loop. operation to become an infinite loop.

Page 23: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

Observer – Example 1

A user presses the File->Load menu item. An A user presses the File->Load menu item. An application object called FileLoader is notified (or application object called FileLoader is notified (or observes the press) and goes about loading a file.observes the press) and goes about loading a file.

Page 24: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

Observer – Example 2

A company that makes medical monitors needs a A company that makes medical monitors needs a way to display data to nurses and physicians so way to display data to nurses and physicians so they can ascertain a patient’s condition quickly they can ascertain a patient’s condition quickly and completely. By using an observer, when new and completely. By using an observer, when new data is added to the database, notifications can be data is added to the database, notifications can be sent to multiple observers, say the monitor at the sent to multiple observers, say the monitor at the patient’s bedside, the nurses’ station and the patient’s bedside, the nurses’ station and the physician who happens to be monitoring the physician who happens to be monitoring the patient live in their office at the same time. patient live in their office at the same time.

Page 25: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

Implementation Points How to map notifying objects to observers. Often How to map notifying objects to observers. Often

down with a simple “connection” function calldown with a simple “connection” function call

Observers may have to know what object is Observers may have to know what object is sending the notification, especially if it registers as sending the notification, especially if it registers as a listener to more than one notifying object. a listener to more than one notifying object.

Similarly, it may also be more efficient to send Similarly, it may also be more efficient to send data each observer rather than sending an update data each observer rather than sending an update message and having each observer retrieve it.message and having each observer retrieve it.

Page 26: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

Deleting an observer should not result in a Deleting an observer should not result in a dangling pointer in the notifying object. A way to dangling pointer in the notifying object. A way to deal with this could be to make each item an deal with this could be to make each item an observer of the other so references can be removed observer of the other so references can be removed when it is deleted.when it is deleted.

A consideration of who triggers the update is very A consideration of who triggers the update is very important. Objects can be responsible for sending important. Objects can be responsible for sending the notification, but if the code is forgotten at the the notification, but if the code is forgotten at the client, or a bug prevents it from being sent, then client, or a bug prevents it from being sent, then the update is never broadcast.the update is never broadcast.

Page 27: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

Push and Pull Models of Implementation. Push and Pull Models of Implementation.

One extreme is the push, which One extreme is the push, which pushespushes data to each data to each observer, without knowing if it needs it or not. This may observer, without knowing if it needs it or not. This may broadcast more information to observers than they need to broadcast more information to observers than they need to know, and make code reuse more difficult.know, and make code reuse more difficult. Most GUI toolkits do thisMost GUI toolkits do this

The pull model sends a relatively simple message, which The pull model sends a relatively simple message, which may require each observer to then request potentially may require each observer to then request potentially identical information. This may hide communication and identical information. This may hide communication and implementation better, but may result in a more inefficient implementation better, but may result in a more inefficient

model.model.

Page 28: Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.

References

““Design Patterns”, Gamma, Helm, Johnson Design Patterns”, Gamma, Helm, Johnson and Vlissides, Addison-Wesley, 1995and Vlissides, Addison-Wesley, 1995