50
CS 4240: Bridge and Abstract Factory Readings: Chap. 10 and 11

CS 4240: Bridge and Abstract Factory Readings: Chap. 10 and 11 Readings: Chap. 10 and 11

Embed Size (px)

Citation preview

Page 1: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

CS 4240: Bridge andAbstract Factory

CS 4240: Bridge andAbstract Factory

Readings: Chap. 10 and 11

Readings: Chap. 10 and 11

Page 2: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Let’s Recap Some Ideas and Strategies

Let’s Recap Some Ideas and Strategies

We’ll assume some design-planning is useful up-front

Design with change in mindChange will happenNot sure exactly what it will beCan predict in advance where it’s

likely to happen

We’ll assume some design-planning is useful up-front

Design with change in mindChange will happenNot sure exactly what it will beCan predict in advance where it’s

likely to happen

Page 3: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

OutlineOutline

First, factory patternsThen, Bridge pattern

First, factory patternsThen, Bridge pattern

Page 4: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

FactoriesFactories

What’s a factory?An object whose responsibilities are

creating one or more objects for clients

Why bother? Why not let client create its own instances?What do you think?

What’s a factory?An object whose responsibilities are

creating one or more objects for clients

Why bother? Why not let client create its own instances?What do you think?

Page 5: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Design Goal of FactoriesDesign Goal of Factories

Sometimes we can separate knowledge of “how to use” from knowledge of “what exactly to create”Client knows first part, factory second part

Abstract class (or interface) vs. object implements that interfaceProgram to abstractionsEncapsulate what varies

Factory provides objects that meet interface but client doesn’t know concrete class of that object

Sometimes we can separate knowledge of “how to use” from knowledge of “what exactly to create”Client knows first part, factory second part

Abstract class (or interface) vs. object implements that interfaceProgram to abstractionsEncapsulate what varies

Factory provides objects that meet interface but client doesn’t know concrete class of that object

Page 6: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Reminder: Static Factory Method

Reminder: Static Factory Method

Static factory methodCoding techniqueClass-level method, returns an

instanceQuestion: what design pattern relied

on thisHint: like factories, also a creational

pattern (a design pattern responsible for creating objects)

Static factory methodCoding techniqueClass-level method, returns an

instanceQuestion: what design pattern relied

on thisHint: like factories, also a creational

pattern (a design pattern responsible for creating objects)

Page 7: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Remember Singleton?Remember Singleton?

Example code: GameMaster gm = GameMaster.getInstance();

Note here a class-level operation returns an instanceNot a separate factory object

Example code: GameMaster gm = GameMaster.getInstance();

Note here a class-level operation returns an instanceNot a separate factory object

Page 8: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Factory Method PatternFactory Method Pattern

Our book doesn’t mention this one, but it’s easy

GoF book intent:Define an interface for creating an object,

but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

Client uses reference to a factory-interface to get an object it needs

Our book doesn’t mention this one, but it’s easy

GoF book intent:Define an interface for creating an object,

but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

Client uses reference to a factory-interface to get an object it needs

Page 9: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Document Processing ExampleDocument Processing Example

Client gets factory object

Asks factory for document

Factory provides some instance

Client doesn’t know exactly what subtype

How does factory know?

Client gets factory object

Asks factory for document

Factory provides some instance

Client doesn’t know exactly what subtype

How does factory know?

Page 10: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Choices and FactoriesChoices and Factories

Might be one factory object that can create different types of objectsClient passes a string or some identifierComments on this kind of design?

(Coupling?)

Often more than one kind of factory objectHow does client get one? Ideas?

Might be one factory object that can create different types of objectsClient passes a string or some identifierComments on this kind of design?

(Coupling?)

Often more than one kind of factory objectHow does client get one? Ideas?

Page 11: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Choices and Factories (cont’d)Choices and Factories (cont’d)Somehow client gets a factory objectSometimes a static method provides this

DocFactory df = DocFactory.getFactory();Note: DocFactory will be abstract class here

How does that method know?One option: stored in configuration file or

Java propertyBottom line: some factor decides, and it’s

“bound” to the client somewhere.What makes sense? Best coupling?

Somehow client gets a factory objectSometimes a static method provides this

DocFactory df = DocFactory.getFactory();Note: DocFactory will be abstract class here

How does that method know?One option: stored in configuration file or

Java propertyBottom line: some factor decides, and it’s

“bound” to the client somewhere.What makes sense? Best coupling?

Page 12: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Example: XML parsingExample: XML parsing

XML documentsMany parsers available, different

strategies, many options for parsingSAXParser is a standard interface

JAXP: an API but not a parserLibraries provide parsers that work

with it

XML documentsMany parsers available, different

strategies, many options for parsingSAXParser is a standard interface

JAXP: an API but not a parserLibraries provide parsers that work

with it

Page 13: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Code sampleCode sample

Typical use:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();factory.setValidating(true); // factory properties

DocumentBuilder builder = factory.newDocumentBuilder();

Document doc = builder.parse(aDocFile);How is parser set? Java properties

Typical use:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();factory.setValidating(true); // factory properties

DocumentBuilder builder = factory.newDocumentBuilder();

Document doc = builder.parse(aDocFile);How is parser set? Java properties

Page 14: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Abstract FactoryAbstract Factory

Intent from GoF:Provide an interface for creating families of

related or dependent objects without specifying their concrete classes

Same idea as beforeSeparate responsibilities of what-to-create

from how-to-use

Difference: families of related objects

Intent from GoF:Provide an interface for creating families of

related or dependent objects without specifying their concrete classes

Same idea as beforeSeparate responsibilities of what-to-create

from how-to-use

Difference: families of related objects

Page 15: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Possible ExamplesPossible Examples

GUIs for multiple platforms etcButton, Label, etc.Different implementations, but all need to

be the same “family”XML docs

Nodes, labels, childrenSame operations but different parsers may

produce different versionsWhat would make this approach work?

What’s common between families?

GUIs for multiple platforms etcButton, Label, etc.Different implementations, but all need to

be the same “family”XML docs

Nodes, labels, childrenSame operations but different parsers may

produce different versionsWhat would make this approach work?

What’s common between families?

Page 16: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

The Abstract in Abstract Factory

The Abstract in Abstract Factory

In this pattern, the factory creates objects called “products” for a common familyFamily could change

What doesn’t change:Each product meets an abstract interfaceE.g. Button is an abstract class, and all

versions meet thatSo client references products as

abstractions

In this pattern, the factory creates objects called “products” for a common familyFamily could change

What doesn’t change:Each product meets an abstract interfaceE.g. Button is an abstract class, and all

versions meet thatSo client references products as

abstractions

Page 17: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Same Ole Song, No?Same Ole Song, No?

What varies:Family defined differences between,

say, two kinds of buttonSo encapsulate this variation

Also, what varies is choice of familySometimes this, another time thatEncapsulate what-to-create inside

Factory object

What varies:Family defined differences between,

say, two kinds of buttonSo encapsulate this variation

Also, what varies is choice of familySometimes this, another time thatEncapsulate what-to-create inside

Factory object

Page 18: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Textbook’s ExampleTextbook’s Example

Client works with a computer’s drivers.

Depending on computer, uses:High Resolution Display Driver and

High Resolution Printer Driver -- OR --

Low Resolution Display Driver and Low Resolution Printer Driver

Client works with a computer’s drivers.

Depending on computer, uses:High Resolution Display Driver and

High Resolution Printer Driver -- OR --

Low Resolution Display Driver and Low Resolution Printer Driver

Page 19: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

You Know to Do ThisYou Know to Do This

Application programs to interfaces But how to make sure always using consistent

objects in one family?

Application programs to interfaces But how to make sure always using consistent

objects in one family?

Page 20: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Use vs. CreateUse vs. Create

Client could take full responsibility for creating objectsSwitch on “selection-factor”Creating a bunch of things from one family

Now client is less cohesiveCoupling: If more families added, family

details change, client must change

Client could take full responsibility for creating objectsSwitch on “selection-factor”Creating a bunch of things from one family

Now client is less cohesiveCoupling: If more families added, family

details change, client must change

Page 21: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Abstract Factory SolutionAbstract Factory Solution

Take what we learned from Factory Method patternAn object is responsible for creating things

for a client to useBut now:

create many different products (e.g. Button, Label, TextField, etc.)

Have one interface for creating all theseClient gets and uses an instance of the

Factory object to create things

Take what we learned from Factory Method patternAn object is responsible for creating things

for a client to useBut now:

create many different products (e.g. Button, Label, TextField, etc.)

Have one interface for creating all theseClient gets and uses an instance of the

Factory object to create things

Page 22: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11
Page 23: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Sequence of EventsSequence of Events

Make sure you understand the order of eventsClient gets a factory of type

ResFactoryWhich one? How does it know?

Calls methods in this ResFactory objects to get products it needs

Uses these references to productsAbstract class or interface

Make sure you understand the order of eventsClient gets a factory of type

ResFactoryWhich one? How does it know?

Calls methods in this ResFactory objects to get products it needs

Uses these references to productsAbstract class or interface

Page 24: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Choice of FactoryChoice of Factory

Again, how does the client choose one factory? Where?Might have a line of code to get a specific

one: ResFactory factory = new LowResFact();

Might be in a configuration fileClass-level method in ResFactoryOther possible ways (user pref, cookie,…)

But: one place to change this!“One rule, one place”

Again, how does the client choose one factory? Where?Might have a line of code to get a specific

one: ResFactory factory = new LowResFact();

Might be in a configuration fileClass-level method in ResFactoryOther possible ways (user pref, cookie,…)

But: one place to change this!“One rule, one place”

Page 25: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

General FormGeneral Form

Page 26: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Our Book Points Out…Our Book Points Out…

Adaptors often used here to make concrete products fit AbstractProduct interface

Switches (or decisions) still here probably, just moved to one place

Adaptors often used here to make concrete products fit AbstractProduct interface

Switches (or decisions) still here probably, just moved to one place

Page 27: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

SummarySummary

Division of responsibilitiesHow to use (client needs to know)What to create

If abstraction used, client doesn’t need to know

Hand off responsibility to factory object

Coupling of client to family-details reduced greatly

Division of responsibilitiesHow to use (client needs to know)What to create

If abstraction used, client doesn’t need to know

Hand off responsibility to factory object

Coupling of client to family-details reduced greatly

Page 28: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11
Page 29: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Bridge PatternBridge Pattern

GoF book’s intent says:De-couple an abstraction from its

implementation so that the two can vary independently

Implementation here means:Not the concrete class that implements an

abstractionInstead, the logic or code that makes the

hard work happenAssume this is in a helper-object

GoF book’s intent says:De-couple an abstraction from its

implementation so that the two can vary independently

Implementation here means:Not the concrete class that implements an

abstractionInstead, the logic or code that makes the

hard work happenAssume this is in a helper-object

Page 30: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

CVA yada yada yada…CVA yada yada yada…

What varies here?First, we have the usual abstraction hierarchy of

IS-A’sSecond, we have multiple ways work gets done

(implementations)These need to be combined

Plan:Encapsulate what variesPrefer aggregation to inheritance

But inheritance is in here tooDon’t use inheritance to combine across dimensions of

variation

What varies here?First, we have the usual abstraction hierarchy of

IS-A’sSecond, we have multiple ways work gets done

(implementations)These need to be combined

Plan:Encapsulate what variesPrefer aggregation to inheritance

But inheritance is in here tooDon’t use inheritance to combine across dimensions of

variation

Page 31: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Book’s ExampleBook’s Example

Client wants to draw shapesHas two drawing programs (engines)

Keep possibility of using either oneBut shapes know which, and client doesn’t

Drawing programs may have different interfaces for drawing primitives

Client wants to draw shapesHas two drawing programs (engines)

Keep possibility of using either oneBut shapes know which, and client doesn’t

Drawing programs may have different interfaces for drawing primitives

Page 32: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Book’s ExampleBook’s Example

ShapesRectangle, Circle, ...

Two drawing "programs" or componentsWe need two versions of each Shape

One uses DP1, the other DP2

“Implementation” here means:the drawing component used for a given

Shape object

ShapesRectangle, Circle, ...

Two drawing "programs" or componentsWe need two versions of each Shape

One uses DP1, the other DP2

“Implementation” here means:the drawing component used for a given

Shape object

Page 33: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

What Might Vary and Where?

What Might Vary and Where?

Drawing programsDifferent methods for primitive drawing

operationsdraw a line, draw a circle

ShapesRules for drawing a rectangle does NOT vary

four lines between corners

So this logic belongs in abstract Rectangle class

Drawing programsDifferent methods for primitive drawing

operationsdraw a line, draw a circle

ShapesRules for drawing a rectangle does NOT vary

four lines between corners

So this logic belongs in abstract Rectangle class

Page 34: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

UML for Shape HierarchyUML for Shape Hierarchy

Page 35: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Linking in the DPsLinking in the DPs

Note four concrete classes2 Shapes x 2 DPs = 4 variations

The “V1 versions” must use a DP1 objectE.g. for V1Rectangle, drawLine() calls DP1’s

draw-a-line methodSo a DP1 object linked to V1Rectangle

See sequence chart, p. 166Note only 3 objects at run-time:

client, someV1Rectangle, theDp1

Note four concrete classes2 Shapes x 2 DPs = 4 variations

The “V1 versions” must use a DP1 objectE.g. for V1Rectangle, drawLine() calls DP1’s

draw-a-line methodSo a DP1 object linked to V1Rectangle

See sequence chart, p. 166Note only 3 objects at run-time:

client, someV1Rectangle, theDp1

Page 36: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11
Page 37: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

What’s the problem(s)?What’s the problem(s)?

Explosion of classesFor each variation of shape, multiply

that by variation in DPCoupling

Every concrete class needs to know its family

Explosion of classesFor each variation of shape, multiply

that by variation in DPCoupling

Every concrete class needs to know its family

Page 38: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Improvement (?)Improvement (?)

Have an abstraction based on shape-typeAbstract class: V1ShapeMove link to particular DP up there

See next UML diagram

Have an abstraction based on shape-typeAbstract class: V1ShapeMove link to particular DP up there

See next UML diagram

Page 39: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11
Page 40: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Better? Problem(s)?Better? Problem(s)?

Class explosion still hereHard to see since 2+2 == 2x2But another DP? 6 concrete classesOr another Shape? 6 concrete classes

RedundancyBoth V1Rectangle and V2Rectangle

have logic of how lines are used to form a rectangle

Class explosion still hereHard to see since 2+2 == 2x2But another DP? 6 concrete classesOr another Shape? 6 concrete classes

RedundancyBoth V1Rectangle and V2Rectangle

have logic of how lines are used to form a rectangle

Page 41: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

The Overall ProblemThe Overall Problem

Need to decouple two abstractionsShape (domain object hierarchy)Drawing program (implementation)

Both varyIndependently

Use aggregation for this coupling/link/relationship

Need to decouple two abstractionsShape (domain object hierarchy)Drawing program (implementation)

Both varyIndependently

Use aggregation for this coupling/link/relationship

Page 42: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Once again:Aggregation separates single “thing”

into two components

Once again:Aggregation separates single “thing”

into two components

Page 43: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

More DetailsMore Details

Page 44: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Two Abstractions in the BridgeTwo Abstractions in the Bridge

Page 45: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Comments on BridgeComments on Bridge

Again, note what’s meant by “implementation” hereWhat a class needs to carry out the job

Note Rectangle and Circle are now concrete classesRules for how-to-draw-myself are hereOne rule, one place! (See p. 179)

Note V1Drawing and V2Drawing (bad names?) are concrete classesQuiz! What pattern is Drawing, V1Drawing, and

DP1?

Again, note what’s meant by “implementation” hereWhat a class needs to carry out the job

Note Rectangle and Circle are now concrete classesRules for how-to-draw-myself are hereOne rule, one place! (See p. 179)

Note V1Drawing and V2Drawing (bad names?) are concrete classesQuiz! What pattern is Drawing, V1Drawing, and

DP1?

Page 46: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Comments on Bridge (2)Comments on Bridge (2)

How does link/connect between a Shape object and a particular Drawing get made?E.g. someRectangle uses V1Drawing objectClient must make this happen

What if clients wants lots of shapes, each using same DP?Have we seen a pattern to help us here?Answer:

How does link/connect between a Shape object and a particular Drawing get made?E.g. someRectangle uses V1Drawing objectClient must make this happen

What if clients wants lots of shapes, each using same DP?Have we seen a pattern to help us here?Answer:

Page 47: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

Real ExamplesReal Examples

Device drivers (e.g. printer drivers)Various types of printer with

variationsB&W, duplex, paper control

Various implementations for particular hardware

JDBC: Java to SQL DB driver

Device drivers (e.g. printer drivers)Various types of printer with

variationsB&W, duplex, paper control

Various implementations for particular hardware

JDBC: Java to SQL DB driver

Page 48: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

AWT WindowsAWT Windows

Page 49: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

SummarySummary

See book for other commentsImportant point about Bridge

Decouple two abstractions that can vary simultaneously

One uses the other to implement functionality

Avoid explosion of subclasses, poor coupling, redundant code

Often used with other patternsß

See book for other commentsImportant point about Bridge

Decouple two abstractions that can vary simultaneously

One uses the other to implement functionality

Avoid explosion of subclasses, poor coupling, redundant code

Often used with other patternsß

Page 50: CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11

ENDEND