Praise For Design Patterns

1y ago
38 Views
2 Downloads
1.18 MB
117 Pages
Last View : 2d ago
Last Download : 2m ago
Upload by : Wren Viola
Transcription

Praise for Design PatternsThis book isn't an introduction to object-oriented technology ordesign. Many books already do a good job of that. This isn't anadvanced treatise either. It's a book of design patterns that describesimple and elegant solutions to specific problems in object-orientedsoftware design.Once you understand the design patterns and have had an "Aha!"(and not just a "Huh?" experience with them, you won't ever thinkabout object-oriented design in the same way. You'll have insights thatcan make your own designs more flexible, modular, reusable, andunderstandable - which is why you're interested in object-orientedtechnology in the first place, right?

IndexINDEX . 5OVERVIEW. 6ABSTRACT FACTORY . 10ADAPTER . 14BRIDGE . 18BUILDER . 24CHAIN OF RESPONSIBILITY . 28COMMAND. 32COMPOSITE . 36DECORATOR . 41FACADE . 47FACTORY METHOD . 51FLYWEIGHT . 56INTERPRETER . 60ITERATOR . 63MEDIATOR . 67MEMENTO . 72NULL OBJECT . 75OBJECT POOL . 80OBSERVER . 84PRIVATE CLASS DATA . 88PROTOTYPE . 90PROXY . 94SINGLETON . 97STATE . 101STRATEGY . 105TEMPLATE METHOD . 109VISITOR . 113ABOUT THE AUTHOR . 119Index 5

OverviewIn software engineering, a design pattern is a general repeatablesolution to a commonly occurring problem in software design. A designpattern isn't a finished design that can be transformed directly into code.It is a description or template for how to solve a problem that can be usedin many different situations.Design patterns can speed up the development process by providingtested, proven development paradigms. Effective software design requiresconsidering issues that may not become visible until later in theimplementation. Reusing design patterns helps to prevent subtle issuesthat can cause major problems and improves code readability for codersand architects familiar with the patterns.Often, people only understand how to apply certain software designtechniques to certain problems. These techniques are difficult to apply toa broader range of problems. Design patterns provide general solutions,documented in a format that doesn't require specifics tied to a particularproblem.In addition, patterns allow developers to communicate using wellknown, well understood names for software interactions. Common designpatterns can be improved over time, making them more robust than adhoc designs.6 Overview

Creational patternsThis design patterns is all about class instantiation. This pattern can befurther divided into class-creation patterns and object-creational patterns.While class-creation patterns use inheritance effectively in theinstantiation process, object-creation patterns use delegation effectivelyto get the job done.Abstract Factory 10Creates an instance of several families of classesBuilder 24Separates object construction from its representationFactory Method 51Creates an instance of several derived classesObject Pool 80Avoid expensive acquisition and release of resources by recyclingobjects that are no longer in usePrototype 90A fully initialized instance to be copied or clonedSingleton 97A class of which only a single instance can existOverview 7

Structural patternsThis design patterns is all about Class and Object composition.Structural class-creation patterns use inheritance to compose interfaces.Structural object-patterns define ways to compose objects to obtain newfunctionality.Adapter 14Match interfaces of different classesBridge 18Separates an object’s interface from its implementationComposite 36A tree structure of simple and composite objectsDecorator 41Add responsibilities to objects dynamicallyFaçade 47A single class that represents an entire subsystemFlyweight 56A fine-grained instance used for efficient sharingPrivate Class Data 88Restricts accessor/mutator accessProxy 94An object representing another object8 Overview

Behavioral patternsThis design patterns is all about Class's objects communication.Behavioral patterns are those patterns that are most specificallyconcerned with communication between objects.Chain of responsibility 28A way of passing a request between a chain of objectsCommand 32Encapsulate a command request as an objectInterpreter 60A way to include language elements in a programIterator 63Sequentially access the elements of a collectionMediator 67Defines simplified communication between classesMemento 72Capture and restore an object's internal stateNull Object 75Designed to act as a default value of an objectObserver 84A way of notifying change to a number of classesState 101Alter an object's behavior when its state changesStrategy 105Encapsulates an algorithm inside a classTemplate method 109Defer the exact steps of an algorithm to a subclassVisitor 113Defines a new operation to a class without changeOverview 9

Abstract FactoryIntent Provide an interface for creating families of related or dependentobjects without specifying their concrete classes. A hierarchy that encapsulates: many possible "platforms", and theconstruction of a suite of "products". The new operator considered harmful.ProblemIf an application is to be portable, it needs to encapsulate platformdependencies. These "platforms" might include: windowing system,operating system, database, etc. Too often, this encapsulatation is notengineered in advance, and lots of #ifdef case statements withoptions for all currently supported platforms begin to procreate likerabbits throughout the code.DiscussionProvide a level of indirection that abstracts the creation of familiesof related or dependent objects without directly specifying theirconcrete classes. The "factory" object has the responsibility forproviding creation services for the entire platform family. Clientsnever create platform objects directly, they ask the factory to do thatfor them.This mechanism makes exchanging product families easy becausethe specific class of the factory object appears only once in theapplication - where it is instantiated. The application can wholesalereplace the entire family of products simply by instantiating a differentconcrete instance of the abstract factory.Because the service provided by the factory object is so pervasive,it is routinely implemented as a Singleton.10 Abstract Factory

StructureThe Abstract Factory defines a Factory Method per product. EachFactory Method encapsulates the new operator and the concrete,platform-specific, product classes. Each "platform" is then modeledwith a Factory derived class.ExampleThe purpose of the Abstract Factory is to provide an interface forcreating families of related objects, without specifying concrete classes.This pattern is found in the sheet metal stamping equipment used inthe manufacture of Japanese automobiles. The stamping equipment isan Abstract Factory which creates auto body parts. The same machineryis used to stamp right hand doors, left hand doors, right front fenders,left front fenders, hoods, etc. for different models of cars. Through theuse of rollers to change the stamping dies, the concrete classes producedby the machinery can be changed within three minutes.Abstract Factory 11

Check list Decide if "platform independence" and creation services are thecurrent source of pain. Map out a matrix of "platforms" versus "products". Define a factory interface that consists of a factory method perproduct. Define a factory derived class for each platform that encapsulates allreferences to the new operator. The client should retire all references to new, and use the factorymethods to create the product objects.Rules of thumbSometimes creational patterns are competitors: there are cases wheneither Prototype or Abstract Factory could be used profitably.At other times they are complementory: Abstract Factory might storea set of Prototypes from which to clone and return product objects,Builder can use one of the other patterns to implement which12 Abstract Factory

components get built. Abstract Factory, Builder, and Prototype can useSingleton in their implementation.Abstract Factory, Builder, and Prototype define a factory object that'sresponsible for knowing and creating the class of product objects, andmake it a parameter of the system. Abstract Factory has the factory objectproducing objects of several classes. Builder has the factory objectbuilding a complex product incrementally using a correspondinglycomplex protocol. Prototype has the factory object (aka prototype)building a product by copying a prototype object.Abstract Factory classes are often implemented with Factory Methods,but they can also be implemented using Prototype.Abstract Factory can be used as an alternative to Facade to hideplatform-specific classes.Builder focuses on constructing a complex object step by step.Abstract Factory emphasizes a family of product objects (either simple orcomplex). Builder returns the product as a final step, but as far as theAbstract Factory is concerned, the product gets returned immediately.Often, designs start out using Factory Method (less complicated, morecustomizable, subclasses proliferate) and evolve toward Abstract Factory,Prototype, or Builder (more flexible, more complex) as the designerdiscovers where more flexibility is needed.Abstract Factory 13

AdapterIntent Convert the interface of a class into another interface clients expect.Adapter lets classes work together that couldn't otherwise because ofincompatible interfaces. Wrap an existing class with a new interface. Impedance match an old component to a new systemProblemAn "off the shelf" component offers compelling functionality thatyou would like to reuse, but its "view of the world" is not compatiblewith the philosophy and architecture of the system currently beingdeveloped.DiscussionReuse has always been painful and elusive. One reason has been thetribulation of designing something new, while reusing something old.There is always something not quite right between the old and the new.It may be physical dimensions or misalignment. It may be timing orsynchronization. It may be unfortunate assumptions or competingstandards.It is like the problem of inserting a new three-prong electrical plug inan old two-prong wall outlet – some kind of adapter or intermediary isnecessary.14 Adapter

Adapter is about creating an intermediary abstraction that translates,or maps, the old component to the new system. Clients call methods onthe Adapter object which redirects them into calls to the legacycomponent. This strategy can be implemented either with inheritance orwith aggregation.Adapter functions as a wrapper or modifier of an existing class. Itprovides a different or translated view of that class.StructureBelow, a legacy Rectangle component's display method expects toreceive "x, y, w, h" parameters. But the client wants to pass "upper leftx and y" and "lower right x and y". This incongruity can be reconciledby adding an additional level of indirection – i.e. an Adapter object.The Adapter could also be thought of as a "wrapper".Adapter 15

ExampleThe Adapter pattern allows otherwise incompatible classes to worktogether by converting the interface of one class into an interfaceexpected by the clients.Socket wrenches provide an example of the Adapter. A socketattaches to a ratchet, provided that the size of the drive is the same.Typical drive sizes in the United States are 1/2" and 1/4".Obviously, a 1/2" drive ratchet will not fit into a 1/4" drive socketunless an adapter is used. A 1/2" to 1/4" adapter has a 1/2" femaleconnection to fit on the 1/2" drive ratchet, and a 1/4" male connection tofit in the 1/4" drive socket.16 Adapter

Check list1. Identify the players: the component(s) that want to beaccommodated (i.e. the client), and the component that needs toadapt (i.e. the adaptee).2. Identify the interface that the client requires.3. Design a "wrapper" class that can "impedance match" the adaptee tothe client.4. The adapter/wrapper class "has a" instance of the adaptee class.5. The adapter/wrapper class "maps" the client interface to the adapteeinterface.6. The client uses (is coupled to) the new interfaceRules of thumbAdapter makes things work after they're designed; Bridge makesthem work before they are.Bridge is designed up-front to let the abstraction and theimplementation vary independently. Adapter is retrofitted to makeunrelated classes work together.Adapter provides a different interface to its subject. Proxy providesthe same interface. Decorator provides an enhanced interface.Adapter is meant to change the interface of an existing object.Decorator enhances another object without changing its interface.Decorator is thus more transparent to the application than an adapter is.As a consequence, Decorator supports recursive composition, whichisn't possible with pure Adapters.Facade defines a new interface, whereas Adapter reuses an oldinterface. Remember that Adapter makes two existing interfaces worktogether as opposed to defining an entirely new one.Adapter 17

BridgeIntent Decouple an abstraction from its implementation so that the two canvary independently. Publish interface in an inheritance hierarchy, and buryimplementation in its own inheritance hierarchy. Beyond encapsulation, to insulationProblem"Hardening of the software arteries" has occurred by usingsubclassing of an abstract base class to provide alternativeimplementations. This locks in compile-time binding between interfaceand implementation. The abstraction and implementation cannot beindependently extended or composed.MotivationConsider the domain of "thread scheduling".There are two types of thread schedulers, and two types of operatingsystems or "platforms". Given this approach to specialization, we haveto define a class for each permutation of these two dimensions. If weadd a new platform (say . Java's Virtual Machine), what would ourhierarchy look like?18 Bridge

What if we had three kinds of thread schedulers, and four kinds ofplatforms? What if we had five kinds of thread schedulers, and tenkinds of platforms? The number of classes we would have to define isthe product of the number of scheduling schemes and the number ofplatforms.The Bridge design pattern proposes refactoring this exponentiallyexplosive inheritance hierarchy into two orthogonal hierarchies – onefor platform-independent abstractions, and the other for platformdependent implementations.DiscussionDecompose the component's interface and implementation intoorthogonal class hierarchies. The interface class contains a pointer tothe abstract implementation class.This pointer is initialized with an instance of a concreteimplementation class, but all subsequent interaction from the interfaceBridge 19

class to the implementation class is limited to the abstraction maintainedin the implementation base class. The client interacts with the interfaceclass, and it in turn "delegates" all requests to the implementation class.The interface object is the "handle" known and used by the client;while the implementation object, or "body", is safely encapsulated toensure that it may continue to evolve, or be entirely replaced (or sharedat run-time.Use the Bridge pattern when: you want run-time binding of the implementation, you have a proliferation of classes resulting from a coupledinterface and numerous implementations, you want to share an implementation among multiple objects, you need to map orthogonal class hierarchies.Consequences include: decoupling the object's interface, improved extensibility (you can extend (i.e. subclass) theabstraction and implementation hierarchies independently), hiding details from clients.Bridge is a synonym for the "handle/body" idiom. This is a designmechanism that encapsulates an implementation class inside of aninterface class.The former is the body, and the latter is the handle. The handle isviewed by the user as the actual class, but the work is done in the body."The handle/body class idiom may be used to decompose a complexabstraction into smaller, more manageable classes. The idiom mayreflect the sharing of a single resource by multiple classes that controlaccess to it (e.g. reference counting)."20 Bridge

StructureThe Client doesn’t want to deal with platform-dependent details. TheBridge pattern encapsulates this complexity behind an abstraction"wrapper".Bridge emphasizes identifying and decoupling "interface"abstraction from "implementation" abstraction.ExampleThe Bridge pattern decouples an abstraction from itsimplementation, so that the two can vary independently.A household switch controlling lights, ceiling fans, etc. is anexample of the Bridge. The purpose of the switch is to turn a device onor off. The actual switch can be implemented as a pull chain, simpletwo position switch, or a variety of dimmer switches.Bridge 21

Check list1. Decide if two orthogonal dimensions exist in the domain. Theseindependent concepts could be: abstraction/platform, ordomain/infrastructure, or front-end/back-end, orinterface/implementation.2. Design the separation of concerns: what does the client want, andwhat do the platforms provide.3. Design a platform-oriented interface that is minimal, necessary, andsufficient. Its goal is to decouple the abstraction from the platform.4. Define a derived class of that interface for each platform.5. Create the abstraction base class that "has a" platform object anddelegates the platform-oriented functionality to it.6. Define specializations of the abstraction class if desired.Rules of thumbAdapter makes things work after they're designed; Bridge makesthem work before they are.22 Bridge

Bridge is designed up-front to let the abstraction and theimplementation vary independently. Adapter is retrofitted to makeunrelated classes work together.State, Strategy, Bridge (and to some degree Adapter) have similarsolution structures. They all share elements of the "handle/body" idiom.They differ in intent - that is, they solve different problems.The structure of State and Bridge are identical (except that Bridgeadmits hierarchies of envelope classes, whereas State allows only one).The two patterns use the same structure to solve different problems:State allows an object's behavior to change along with its state, whileBridge's intent is to decouple an abstraction from its implementation sothat the two can vary independently.If interface classes delegate the creation of their implementationclasses (instead of creating/coupling themselves directly), then thedesign usually uses the Abstract Factory pattern to create theimplementation objects.Bridge 23

BuilderIntent Separate the construction of a complex object from its representationso that the same construction process can create differentrepresentations. Parse a complex representation, create one of several targets.ProblemAn application needs to create the elements of a complex aggregate.The specification for the aggregate exists on secondary storage and oneof many representations needs to be built in primary storage.DiscussionSeparate the algorithm for interpreting (i.e. reading and parsing) astored persistence mechanism (e.g. RTF files) from the algorithm forbuilding and representing one of many target products (e.g. ASCII,TeX, text widget). The focus/distinction is on creating complexaggregates.The "director" invokes "builder" services as it interprets the externalformat. The "builder" creates part of the complex object each time it iscalled and maintains all intermediate state. When the product isfinished, the client retrieves the result from the "builder".Affords finer control over the construction process. Unlike creationalpatterns that construct products in one shot, the Builder patternconstructs the product step by step under the control of the "director".StructureThe Reader encapsulates the parsing of the common input. TheBuilder hierarchy makes possible the polymorphic creation of manypeculiar representations or targets.24 Builder

ExampleThe Builder pattern separates the construction of a complex objectfrom its representation so that the same construction process can createdifferent representations.This pattern is used by fast food restaurants to construct children'smeals. Children's meals typically consist of a main item, a side item, adrink, and a toy (e.g., a hamburger, fries, Coke, and toy dinosaur). Notethat there can be variation in the content of the children's meal, but theconstruction process is the same.Whether a customer orders a hamburger, cheeseburger, or chicken,the process is the same. The employee at the counter directs the crew toassemble a main item, side item, and toy. These items are then placed ina bag. The drink is placed in a cup and remains outside of the bag. Thissame process is used at competing restaurants.Builder 25

Check list1. Decide if a common input and many possible representations (oroutputs) is the problem at hand.2. Encapsulate the parsing of the common input in a Reader class.3. Design a standard protocol for creating all possible outputrepresentations. Capture the steps of this protocol in a Builderinterface.4. Define a Builder derived class for each target representation.5. The client creates a Reader object and a Builder object, and registersthe latter with the former.6. The client asks the Reader to "construct".7. The client asks the Builder to return the result.26 Builder

Rules of thumbSometimes creational patterns are complementory: Builder can useone of the other patterns to implement which components get built.Abstract Factory, Builder, and Prototype can use Singleton in theirimplementations.Builder focuses on constructing a complex object step by step.Abstract Factory emphasizes a family of product objects (either simpleor complex). Builder returns the product as a final step, but as far as theAbstract Factory is concerned, the product gets returned immediately.Builder often builds a Composite.Often, designs start out using Factory Method (less complicated,more customizable, subclasses proliferate) and evolve toward AbstractFactory, Prototype, or Builder (more flexible, more complex) as thedesigner discovers where more flexibility is needed.Builder 27

Chain of ResponsibilityIntent Avoid coupling the sender of a request to its receiver by giving morethan one object a chance to handle the request. Chain the receivingobjects and pass the request along the chain until an object handlesit. Launch-and-leave requests with a single processing pipeline thatcontains many possible handlers. An object-oriented linked list with recursive traversal.ProblemThere is a potentially variable number of "handler" or "processingelement" or "node" objects, and a stream of requests that must behandled. Need to efficiently process the requests without hard-wiringhandler relationships and precedence, or request-to-handler mappings.DiscussionEncapsulate the processing elements inside a "pipeline" abstraction;and have clients "launch and leave" their requests at the entrance to thepipeline.28 Chain of Responsibility

The pattern chains the receiving objects together, and then passesany request messages from object to object until it reaches an objectcapable of handling the message. The number and type of handlerobjects isn't known a priori, they can be configured dynamically. Thechaining mechanism uses recursive composition to allow an unlimitednumber of handlers to be linked.Chain of Responsibility simplifies object interconnections. Insteadof senders and receivers maintaining references to all candidatereceivers, each sender keeps a single reference to the head of the chain,and each receiver keeps a single reference to its immediate successor inthe chain.Make sure there exists a "safety net" to "catch" any requests whichgo unhandled.Do not use Chain of Responsibility when each request is onlyhandled by one handler, or, when the client object knows which serviceobject should handle the request.StructureThe derived classes know how to satisfy Client requests. If the"current" object is not available or sufficient, then it delegates to thebase class, which delegates to the "next" object, and the circle of lifecontinues.Chain of Responsibility 29

Multiple handlers could contribute to the handling of each request.The request can be passed down the entire length of the chain, with thelast link being careful not to delegate to a "null next".ExampleThe Chain of Responsibility pattern avoids coupling the sender of arequest to the receiver by giving more than one object a chance tohandle the request. ATM use the Chain of Responsibility in moneygiving mechanism.30 Chain of Responsibility

Check list1. The base class maintains a "next" pointer.2. Each derived class implements its contribution for handling therequest.3. If the request needs to be "passed on", then the derived class "callsback" to the base class, which delegates to the "next" pointer.4. The client (or some third party) creates and links the chain (whichmay include a link from the last node to the root node).5. The client "launches and leaves" each request with the root of thechain.6. Recursive delegation produces the illusion of magic.Rules of thumbChain of Responsibility, Command, Mediator, and Observer, addresshow you can decouple senders and receivers, but with different tradeoffs. Chain of Responsibility passes a sender request along a chain ofpotential receivers.Chain of Responsibility can use Command to represent requests asobjects.Chain of Responsibility is often applied in conjunction withComposite. There, a component's parent can act as its successor.Chain of Responsibility 31

CommandIntent Encapsulate a request as an object, thereby letting you parameterizeclients with different requests, queue or log requests, and supportundoable operations. Promote "invocation of a method on an object" to full object status An object-oriented callbackProblemNeed to issue requests to objects without knowing anything aboutthe operation being requested or the receiver of the request.DiscussionCommand decouples the object that invokes the operation from theone that knows how to perform it. To achieve this separation, thedesigner creates an abstract base class that maps a receiver (an object)with an action (a pointer to a member function). The base class containsan execute method that simply calls the action on the receiver.All clients of Command objects treat each object as a "black box" bysimply invoking the object's virtual execute method whenever theclient requires the object's "service".A Command class holds some subset of the following: an object, amethod to be applied to the object, and the arguments to be passed whenthe method is applied. The Command's "execute" method then causesthe pieces to come together.Sequences of Command objects can be assembled into composite (ormacro) commands.StructureThe client that creates a command is not the same client thatexecutes it. This separation provides flexibility in the timing andsequencing of commands. Materializing commands as objects means32 Command

they can be passed, staged, shared, loaded in a table, and otherwiseinstrumented or manipulated like any other object.Command objects can be thought of as "tokens" that are created byone client that knows what need to be done, and passed to

Creational patterns This design patterns is all about class instantiation. This pattern can be further divided into class-creation patterns and object-creational patterns. While class-creation patterns use inheritance effectively in the instantiation process, object-creation patterns

Related Documents:

Song of Praise Knut Nystedt Praise the Lord! Praise the Lord from the heavens. Praise the Lord! Praise the Lord in the heights. Praise him all his angels, praise him all his hosts. Praise him sun and moon, praise him all you shining stars! Praise him you highest heavens, and the waters above the heavens.

Bruksanvisning för bilstereo . Bruksanvisning for bilstereo . Instrukcja obsługi samochodowego odtwarzacza stereo . Operating Instructions for Car Stereo . 610-104 . SV . Bruksanvisning i original

10 tips och tricks för att lyckas med ert sap-projekt 20 SAPSANYTT 2/2015 De flesta projektledare känner säkert till Cobb’s paradox. Martin Cobb verkade som CIO för sekretariatet för Treasury Board of Canada 1995 då han ställde frågan

service i Norge och Finland drivs inom ramen för ett enskilt företag (NRK. 1 och Yleisradio), fin ns det i Sverige tre: Ett för tv (Sveriges Television , SVT ), ett för radio (Sveriges Radio , SR ) och ett för utbildnings program (Sveriges Utbildningsradio, UR, vilket till följd av sin begränsade storlek inte återfinns bland de 25 största

Hotell För hotell anges de tre klasserna A/B, C och D. Det betyder att den "normala" standarden C är acceptabel men att motiven för en högre standard är starka. Ljudklass C motsvarar de tidigare normkraven för hotell, ljudklass A/B motsvarar kraven för moderna hotell med hög standard och ljudklass D kan användas vid

LÄS NOGGRANT FÖLJANDE VILLKOR FÖR APPLE DEVELOPER PROGRAM LICENCE . Apple Developer Program License Agreement Syfte Du vill använda Apple-mjukvara (enligt definitionen nedan) för att utveckla en eller flera Applikationer (enligt definitionen nedan) för Apple-märkta produkter. . Applikationer som utvecklas för iOS-produkter, Apple .

Oh, praise Him, Alleluia Thou rising moon in praise rejoice Ye lights of evening find a voice Oh, praise Him, Oh, praise Him Alleluia, Alleluia, Alleluia Let all things their creator bless And worship Him in humbleness Oh, praise Him, Alleluia

O praise Him, O praise Him! Alleluia! Alleluia! Allelu-u-ia! Thou rushing wind that art so strong, Ye clouds that sail in heav'n along, O praise Him! Alleluia! Thou rising morn, in praise rejoice, Ye lights of evening, find a voice! O praise Him, O praise Him! Alleluia! Alleluia! Alleluia! A