1 Advanced Object-oriented Design – Principles and Patterns Structural Design Patterns.
-
Upload
may-knight -
Category
Documents
-
view
250 -
download
1
Transcript of 1 Advanced Object-oriented Design – Principles and Patterns Structural Design Patterns.
1
Advanced Object-oriented Advanced Object-oriented Design – Principles and Design – Principles and
PatternsPatterns Structural Design PatternsStructural Design Patterns
2
Summarizing the Design ThemesSummarizing the Design ThemesThink differently about Types Vs. ClassesThink differently about Types Vs. ClassesProgram to an interface (Type), not an Program to an interface (Type), not an
implementation (Class).implementation (Class).
Favor object composition over class inheritance, Favor object composition over class inheritance, black box over white box reuse.black box over white box reuse.
Design relationships betweenDesign relationships betweenobjects and their types to achieve good run-time objects and their types to achieve good run-time
structure. Don’t limit yourself to compile time structure. Don’t limit yourself to compile time structures.structures.
3
Structural Design PatternsStructural Design Patterns Concerned with how classes and objects are Concerned with how classes and objects are
composed to form larger structurescomposed to form larger structures Structural class patterns use inheritance to Structural class patterns use inheritance to
compose interfaces or implementationscompose interfaces or implementations Structural object patterns describe ways to Structural object patterns describe ways to
compose objects to realize new compose objects to realize new functionalityfunctionality
4
Topic 1: Adapter PatternTopic 1: Adapter Pattern
Convert the interface of a class into another Convert the interface of a class into another interface clients expect. Adapter lets classes interface clients expect. Adapter lets classes
work together that couldn't otherwise because work together that couldn't otherwise because of incompatible interfaces.of incompatible interfaces.
5
Adapter: ApplicabilityAdapter: Applicability you want to use an existing class, and its you want to use an existing class, and its
interface does not match the one you need.interface does not match the one you need. you want to create a reusable class that you want to create a reusable class that
cooperates with unrelated or unforeseen cooperates with unrelated or unforeseen classes, that is, classes that don't necessarily classes, that is, classes that don't necessarily have compatible interfaces.have compatible interfaces.
you need to use several existing subclasses, you need to use several existing subclasses, but it's impractical to adapt their interface but it's impractical to adapt their interface by subclassing every one.by subclassing every one.
6
Adapter: ExampleAdapter: Example
Application
add(d : Document)
HPPrintDriver
printFile(fileName : String)
HPPrintInterface
printDocument(fileName : String)
+theHPPrintDriver
return theHPPrintDriver.printFile (fileName);
IPrintInterface
printDocument(fileName : String)
<<Interface>>
+theIPrintInterface
7
Adapter: ModelAdapter: Model
ClientTarget
request()
Adapter
request()
Adaptee
specificRequest()
+adaptee
return adaptee.specificRequest ();
8
Adapter: CollaborationsAdapter: Collaborations Target (PrintInterface) defines the domain-Target (PrintInterface) defines the domain-
specific interface that Client uses. specific interface that Client uses. Client (Application) collaborates with Client (Application) collaborates with
objects conforming to the Target interface. objects conforming to the Target interface. Adaptee (HPPrintDriver) defines an Adaptee (HPPrintDriver) defines an
existing interface that needs adapting. existing interface that needs adapting. Adapter (HPPrintInterface) adapts the Adapter (HPPrintInterface) adapts the
interface of Adaptee to the Target interface. interface of Adaptee to the Target interface.
9
Adapter: ConsequencesAdapter: Consequences Variation: Instead of delegating to an Variation: Instead of delegating to an
Adaptee, can an Adapter inherit from an Adaptee, can an Adapter inherit from an Adaptee ? What are the consequences ?Adaptee ? What are the consequences ?
The amount of work Adapter does depends The amount of work Adapter does depends on how similar the Target interface is to on how similar the Target interface is to Adaptee's; Varies from simple interface Adaptee's; Varies from simple interface conversion to providing complex operationsconversion to providing complex operations
10
Adapter: ExerciseAdapter: Exercise As part of you enterprise application you are As part of you enterprise application you are
required to make use of a messaging middleware required to make use of a messaging middleware such as MQSeries. Your application wants to send such as MQSeries. Your application wants to send and rececive messages to other subsystems (such and rececive messages to other subsystems (such as billing system, and decision support system). as billing system, and decision support system). However, depending on the installation you want However, depending on the installation you want to support multiple message oriented middleware to support multiple message oriented middleware products in the near future (such as products in the near future (such as DECMessageQ, MS MQ etc.). Could the Adapter DECMessageQ, MS MQ etc.). Could the Adapter pattern provide you a solution ?pattern provide you a solution ?
11
Topic 2: Proxy PatternTopic 2: Proxy Pattern
Provide a surrogate or placeholder Provide a surrogate or placeholder for another object to control access for another object to control access
to it.to it.
12
Proxy: ApplicabilityProxy: Applicability A remote proxy provides a local A remote proxy provides a local
representative for an object in a different representative for an object in a different address space.address space.
A virtual proxy creates expensive objects A virtual proxy creates expensive objects on demand. on demand.
A protection proxy controls access to the A protection proxy controls access to the original object. original object.
13
Proxy: ExampleProxy: Example
Client
BusinessObjectImpl
service1(data : String) : Stringservice2(data : String) : String
BusinessObjectSkeleton
service1(data : String) : Stringservice2(data : String) : String
localCall
BusinessObjectProxy
service1(data : String) : Stringservice2(data : String) : String
remoteCall
IBusinessObject
service1(data : String) : Stringservice2(data : String) : String
<<Interface>>
+theBusinessObject
+theBusinessObjectSkeleton +theBusinessObjectImpl
14
Proxy: ModelProxy: Model
SubjectProxy
request()
SubjectReal
request()
ClientSubject
request()
realSubject
return realSubject.request();
15
Proxy: CollaborationsProxy: Collaborations Proxy (BusinessObjectProxy) Proxy (BusinessObjectProxy)
» maintains a reference that lets the proxy access the real subject. Proxy maintains a reference that lets the proxy access the real subject. Proxy may refer to a Subject if the RealSubject and Subject interfaces are the may refer to a Subject if the RealSubject and Subject interfaces are the same. same.
» provides an interface identical to Subject's so that a proxy can by provides an interface identical to Subject's so that a proxy can by substituted for the real subject. substituted for the real subject.
» controls access to the real subject and may be responsible for creating controls access to the real subject and may be responsible for creating and deleting it. and deleting it.
» remote proxies are responsible for encoding a request and its arguments remote proxies are responsible for encoding a request and its arguments and for sending the encoded request to the real subject in a different and for sending the encoded request to the real subject in a different address space; protection proxies check that the caller has the access address space; protection proxies check that the caller has the access permissions required to perform a request. permissions required to perform a request.
Subject (BusinessObjectInterface) defines the common Subject (BusinessObjectInterface) defines the common interface for RealSubject and Proxy so that a Proxy can be interface for RealSubject and Proxy so that a Proxy can be used anywhere a RealSubject is expected. used anywhere a RealSubject is expected.
RealSubject (BusinessObjectImpl) defines the real object RealSubject (BusinessObjectImpl) defines the real object that the proxy represents. that the proxy represents.
16
Proxy: ConsequencesProxy: Consequences A remote proxy can hide the fact that an A remote proxy can hide the fact that an
object resides in a different address space. object resides in a different address space. A virtual proxy can perform optimizations A virtual proxy can perform optimizations
such as creating an object on demand. such as creating an object on demand. Both protection proxies allow for additional Both protection proxies allow for additional
housekeeping tasks (such as security housekeeping tasks (such as security verification) when an object is accessed. verification) when an object is accessed.
17
Proxy: ExerciseProxy: Exercise The logical subscription data object representing The logical subscription data object representing
the logical record in memory aggregates multiple the logical record in memory aggregates multiple physical data records such as payment records, physical data records such as payment records, subscription details, credit status etc. The subscription details, credit status etc. The application retrieves a set of logical subscription application retrieves a set of logical subscription objects while processing renewals, but has the objects while processing renewals, but has the need to examine the detailed records only on need to examine the detailed records only on certain subscriptions. For performance reasons, certain subscriptions. For performance reasons, uou would like to avoid loading the subscription uou would like to avoid loading the subscription data that may not be used. Hence you decide to data that may not be used. Hence you decide to implement a load on demand scheme where by the implement a load on demand scheme where by the actual subscription data is loaded as and when actual subscription data is loaded as and when needed by the application. Employ proxy pattern.needed by the application. Employ proxy pattern.
18
Topic 3: Facade PatternTopic 3: Facade Pattern
Provide a unified interface to a set of Provide a unified interface to a set of interfaces in a subsystem. Facade defines a interfaces in a subsystem. Facade defines a
higher-level interface that makes the higher-level interface that makes the subsystem easier to use.subsystem easier to use.
19
Facade: ApplicabilityFacade: Applicability Hiding complexity: To provide a simple interface to a complex Hiding complexity: To provide a simple interface to a complex
subsystem. Subsystems often get more complex as they evolve. subsystem. Subsystems often get more complex as they evolve. A facade can provide a simple default view of the subsystem A facade can provide a simple default view of the subsystem that is good enough for most clients. Only clients needing that is good enough for most clients. Only clients needing more customizability will need to look beyond the facade. more customizability will need to look beyond the facade.
Reducing dependency: there are many dependencies between Reducing dependency: there are many dependencies between clients and the implementation classes of an abstraction. clients and the implementation classes of an abstraction. Introduce a facade to decouple the subsystem from clients and Introduce a facade to decouple the subsystem from clients and other subsystems, thereby promoting subsystem independence other subsystems, thereby promoting subsystem independence and portability. and portability.
Define entry points and layer subsystems: Use a facade to Define entry points and layer subsystems: Use a facade to define an entry point to each subsystem level. If subsystems define an entry point to each subsystem level. If subsystems are dependent, then you can simplify the dependencies are dependent, then you can simplify the dependencies between them by making them communicate with each other between them by making them communicate with each other solely through their facades. solely through their facades.
20
Facade: ExampleFacade: Example
Scanner
scan(fileName : String)
Parser
parse(data : String)
TypeChecker
check(data : String)
ByteCodeGenerator
generate(data : String)
ProgramNodeGenerator
generate(data : String)
Statement Expression Variable Literal
Token
create(data : String)
ProgramNode
execute()
Compiler
compile(fileName : String)
Application
add(d : Document)
+theCompiler
+theToken
21
Facade: ModelFacade: Model
Application Facade
Class1 Class2 Class3 ClassN
22
Facade: CollaborationsFacade: Collaborations Facade (Compiler) Facade (Compiler)
– knows which subsystem classes are responsible for a knows which subsystem classes are responsible for a request. request.
– delegates client requests to appropriate subsystem delegates client requests to appropriate subsystem objects. objects.
Subsystem classes (Scanner, Parser, Subsystem classes (Scanner, Parser, ProgramNode, etc.) ProgramNode, etc.) – implement subsystem functionality. implement subsystem functionality.
– handle work assigned by the Facade object. handle work assigned by the Facade object.
– have no knowledge of the facade; that is, they keep no have no knowledge of the facade; that is, they keep no references to it. references to it.
23
Facade: ConsequencesFacade: Consequences shields clients from subsystem components, thereby shields clients from subsystem components, thereby
reducing the number of objects that clients deal with and reducing the number of objects that clients deal with and making the subsystem easier to use. making the subsystem easier to use.
promotes weak coupling between the subsystem and its promotes weak coupling between the subsystem and its clients. Often the components in a subsystem are strongly clients. Often the components in a subsystem are strongly coupled. Weak coupling lets you vary the components of coupled. Weak coupling lets you vary the components of the subsystem without affecting its clients. the subsystem without affecting its clients.
help layer a system and the dependencies between objects; help layer a system and the dependencies between objects; eliminates complex or circular dependencies. eliminates complex or circular dependencies.
Reducing compilation dependencies is vital in large Reducing compilation dependencies is vital in large software systems.software systems.
It doesn't prevent applications from using subsystem It doesn't prevent applications from using subsystem classes if they need to.classes if they need to.
24
Facade: ExerciseFacade: Exercise You are to design a subsystem that takes in subscriptions You are to design a subsystem that takes in subscriptions
over the Internet. Behind the scene there is a lot involved over the Internet. Behind the scene there is a lot involved in taking in a subscription. For example, you need to in taking in a subscription. For example, you need to figure if this is a new subscription or a renewal. You need figure if this is a new subscription or a renewal. You need to locate the customer data if the subscription is from a to locate the customer data if the subscription is from a repeat customer. You need to verify the credit status of the repeat customer. You need to verify the credit status of the customer and the payment details of the subscription customer and the payment details of the subscription before accepting it. Based on the customer profile you before accepting it. Based on the customer profile you may want to promote cross selling by suggesting may want to promote cross selling by suggesting additional products the subscriber may be interested in. additional products the subscriber may be interested in. Additionally you need to update a Decision Support Additionally you need to update a Decision Support system with the new subscription on successful creation. system with the new subscription on successful creation. Discuss how the Façade pattern may be useful.Discuss how the Façade pattern may be useful.
25
Topic 4: Decorator PatternTopic 4: Decorator Pattern
Attach additional responsibilities to an object Attach additional responsibilities to an object dynamically. Decorators provide a flexible dynamically. Decorators provide a flexible
alternative to sub-classing for extending alternative to sub-classing for extending functionality.functionality.
26
Decorator: ApplicabilityDecorator: Applicability You want to add responsibilities to You want to add responsibilities to
individual objects dynamically, not to an individual objects dynamically, not to an entire classentire class
Modeling for responsibilities that can be Modeling for responsibilities that can be withdrawn.withdrawn.
You want clients to be able to ignore the You want clients to be able to ignore the difference between objects and decorated difference between objects and decorated object instances. object instances.
recursively allows an open-ended number recursively allows an open-ended number of additional responsibilitiesof additional responsibilities
27
Decorator : ExampleDecorator : Example
TextView
draw()
ScrollDecorator
draw()scroll()
BorderDecorator
draw()drawBoarder()
Decorator
draw()
VisualComponent
draw()
<<Interface>>
1
+myComponent
1
void draw () { super.draw (); drawBorder();}
void draw () { myComponent.draw ();}
28
Decorator : CollaborationsDecorator : Collaborations Component (VisualComponent) Component (VisualComponent)
– defines the interface for objects that can have responsibilities defines the interface for objects that can have responsibilities added to them dynamically. added to them dynamically.
Concrete Component (Text View) Concrete Component (Text View) – defines an object to which additional responsibilities can be defines an object to which additional responsibilities can be
attached. attached.
Decorator (Decorator) Decorator (Decorator) – maintains a reference to a Component objectmaintains a reference to a Component object
– defines an interface that conforms to Component's interface. . defines an interface that conforms to Component's interface. .
ConcreteDecorator (BorderDecorator)ConcreteDecorator (BorderDecorator)
– adds responsibilities to the component.adds responsibilities to the component.
29
Decorator : ConsequencesDecorator : Consequences More flexibility than static inheritance: responsibilities can More flexibility than static inheritance: responsibilities can
be added and removed at run-time simply by attaching and be added and removed at run-time simply by attaching and detaching them. In contrast, inheritance requires creating a detaching them. In contrast, inheritance requires creating a new class for each additional responsibility new class for each additional responsibility (BorderedTextView)(BorderedTextView)
Pay-as-you-go approach: Instead of trying to support all Pay-as-you-go approach: Instead of trying to support all foreseeable features in a complex, customizable class, you foreseeable features in a complex, customizable class, you can define a simple class and add functionality can define a simple class and add functionality incrementally with Decorator objects. Functionality can be incrementally with Decorator objects. Functionality can be composed from simple pieces. As a result, an application composed from simple pieces. As a result, an application needn't pay for features it doesn't useneedn't pay for features it doesn't use
A decorator and its component aren't identicalA decorator and its component aren't identical Lots of little objects: results in systems composed of lots Lots of little objects: results in systems composed of lots
of little objects that all look alikeof little objects that all look alike
30
Decorator : ExerciseDecorator : Exercise As part of your on-line subscription site you As part of your on-line subscription site you
decide to support logging functionality. decide to support logging functionality. That is, you want an log entry to be That is, you want an log entry to be generated every time a PublishedData generated every time a PublishedData object is opened in a Write mode and the object is opened in a Write mode and the content of the data object modified. The content of the data object modified. The logging functionality is not needed when logging functionality is not needed when the Published data is accessed in a read only the Published data is accessed in a read only mode.mode.
31
Topic 5: Composite PatternTopic 5: Composite Pattern
Compose objects into tree structures to Compose objects into tree structures to represent part-whole hierarchies. Composite represent part-whole hierarchies. Composite
lets clients treat individual objects and lets clients treat individual objects and compositions of objects uniformly.compositions of objects uniformly.
32
Composite: ApplicabilityComposite: Applicability you want to represent part-whole you want to represent part-whole
hierarchies of objects. hierarchies of objects. you want clients to be able to ignore the you want clients to be able to ignore the
difference between compositions of objects difference between compositions of objects and individual objects. Clients will treat all and individual objects. Clients will treat all objects in the composite structure objects in the composite structure uniformly. uniformly.
33
Composite: ExampleComposite: Example
Line
draw()move()
Text
draw()move()
Circle
draw()move()
IGraphic aGraphic = null; Enumeration e = myComponents.elements (); while (e.hasMoreElements ()) { aGraphic = (IGraphic) e.nextElement ():
aGraphic.draw (); }
Picture
draw()move()addGraphic(g : Graphic)removeGraphic(g : Graphic)getChildren()
GraphicEditorIGraphic
<<Interface>>
0..*0..*
+myComponents+myGraphics
34
Composite: ModelComposite: Model
Leaf
operation()
Client
Composite
operation()add(c : Component)remove(c : Component)getChildren() : VectorgetChild(id : int) : Component
Component
operation()add(c : Component)remove(c : Component)getChildren() : VectorgetChild(id : int) : Component 0..*
myComponents
operation () { for all c in myComponents
c.operation ();}
0..*
35
Composite: CollaborationsComposite: Collaborations Component (Graphic) Component (Graphic)
– declares the interface for objects in the composition.declares the interface for objects in the composition.– implements default behavior for the interface common to all classes, as implements default behavior for the interface common to all classes, as
appropriate. appropriate. – declares an interface for accessing and managing its child components. declares an interface for accessing and managing its child components. – (optional) defines an interface for accessing a component's parent in the (optional) defines an interface for accessing a component's parent in the
recursive structure, and implements it if that's appropriate. recursive structure, and implements it if that's appropriate. Leaf (Line, Text, etc.) Leaf (Line, Text, etc.)
– represents leaf objects in the composition. A leaf has no children. represents leaf objects in the composition. A leaf has no children. – defines behavior for primitive objects in the composition. defines behavior for primitive objects in the composition.
Composite (Picture) Composite (Picture) – defines behavior for components having children. defines behavior for components having children. – stores child components. stores child components. – implements child-related operations in the Component interface. implements child-related operations in the Component interface.
Client (GraphicEditor) manipulates objects in the composition through Client (GraphicEditor) manipulates objects in the composition through
the Component interface.the Component interface.
36
Composite: ConsequencesComposite: Consequences defines class hierarchies consisting of primitive objects and composite defines class hierarchies consisting of primitive objects and composite
objects. Primitive objects can be composed into more complex objects, objects. Primitive objects can be composed into more complex objects, which in turn can be composed, and so on recursively. Wherever client which in turn can be composed, and so on recursively. Wherever client code expects a primitive object, it can also take a composite object. code expects a primitive object, it can also take a composite object.
makes the client simple. Clients can treat composite structures and makes the client simple. Clients can treat composite structures and individual objects uniformly. Clients normally don't know (and individual objects uniformly. Clients normally don't know (and shouldn't care) whether they're dealing with a leaf or a composite shouldn't care) whether they're dealing with a leaf or a composite component. This simplifies client code, because it avoids having to component. This simplifies client code, because it avoids having to write tag-and-case-statement-style functions over the classes that write tag-and-case-statement-style functions over the classes that define the composition. define the composition.
makes it easier to add new kinds of components. Newly defined makes it easier to add new kinds of components. Newly defined Composite or Leaf subclasses work automatically with existing Composite or Leaf subclasses work automatically with existing structures and client code. Clients don't have to be changed for new structures and client code. Clients don't have to be changed for new Component classes. Component classes.
can make your design overly general; makes it harder to restrict the can make your design overly general; makes it harder to restrict the
components of a composite.components of a composite.
37
Composite: ExerciseComposite: Exercise As part of your on-line subscription site you As part of your on-line subscription site you
decide to promote certain products. These decide to promote certain products. These products may be simple products or products that products may be simple products or products that are packages of other products which in turn may are packages of other products which in turn may be packages of other products and so on. The be packages of other products and so on. The customer may decide to buy products separately or customer may decide to buy products separately or as part of a package deal where they buy a set of as part of a package deal where they buy a set of related products packaged together. You need to related products packaged together. You need to write a pricing module which can price products write a pricing module which can price products individually or in packages. Could composite individually or in packages. Could composite pattern be used ? Would your pricing module pattern be used ? Would your pricing module benefit ? benefit ?
38
Resources: Principles and PatternsResources: Principles and Patterns Designing Object-Oriented C++ Applications Designing Object-Oriented C++ Applications
using the Booch Method By Robert C. Martin using the Booch Method By Robert C. Martin (1994) (1994)
Design Patterns by Erich Gamma, Richard Helm, Design Patterns by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, Grady BoochRalph Johnson, John Vlissides, Grady Booch
http://www.cetus-links.org/oo_patterns.htmlhttp://www.cetus-links.org/oo_patterns.html http://hillside.net/patterns/patterns.htmlhttp://hillside.net/patterns/patterns.html http://theserverside.com/home/index.jsphttp://theserverside.com/home/index.jsp http://www.cs.wustl.edu/~schmidt/patterns.htmlhttp://www.cs.wustl.edu/~schmidt/patterns.html