Upload
kiranshingote
View
215
Download
0
Embed Size (px)
Citation preview
7/29/2019 designPatterns-11.pdf
1/32
Structure Patters:
Bridgeand
Flyweight
CSCI 3132 Summer 2011 1
7/29/2019 designPatterns-11.pdf
2/32
IntroducingtheBridgePa1ern
IntentTodecoupleanabstrac7onfromitsimplementa7onsothatthetwocanvary
independently.
Whatdoesitmean? Decouple:havethingsbehaveindependentlyfromeachother.
Abstrac7on:howthingsarerelatedtoeachotherconceptually.
2
7/29/2019 designPatterns-11.pdf
3/32
AnExample Asimpleproblem
Drawingshapes Rectangles
Twodifferentdrawingprograms
3
7/29/2019 designPatterns-11.pdf
4/32
Example(Contd) Properuseofinheritance
Wedontwantthecodethatdrawstherectanglestoworryaboutwhattypeofdrawingprogramitshoulduse.
VRectangleusesDP V2RectangleusesDP2
class V1Rectangle : public Rectangle!{!public:!
V1Rectangle(double x1, double y1, double x2, double y2) : !Rectangle(x1, y1, x2, y2){} !
void drawLine( double x1, double y1, double x2, double y2){!DP1::draw_a_line( x1, y1, x2, y2);!
}!public:!
~V1Rectangle(void);!};!
4
7/29/2019 designPatterns-11.pdf
5/32
ADesignusingInheritance
Changing requirements: add a new shape - circle
5
7/29/2019 designPatterns-11.pdf
6/32
SequenceDiagram
6
7/29/2019 designPatterns-11.pdf
7/32
AnyProblem? Combinatorialexplosion
Anothernewdrawingprogram SixdifferentkindsofShapes
2Shapeconcepts7mesthreedrawingprogramsAnothertypeofShape
NinedifferentkindsofShapes3Shapeconcepts7mesthreedrawingprograms
7
7/29/2019 designPatterns-11.pdf
8/32
LearningtheBridgePa1ern:
AnExample Reason
Tightlycoupled Theabstrac7on(thekindsofShapes)andtheimplementa7on(thedrawingprograms)
TheBridgepa1ern Todecoupleanabstrac7onfromitsimplementa7onso
thatthetwocanvaryindependently
8
7/29/2019 designPatterns-11.pdf
9/32
AnObserva7on Thewaytolookatdesignpa1erns
Focusonthecontextofthepa1erntheproblemitistryingtosolve
Notonthesolu7onsthepa1ernsoffer Thebridgepa1ern
Anabstrac7onthathasdifferentimplementa7ons Allowtheabstrac7onandtheimplementa7ontovary
independentlyofeachother
9
7/29/2019 designPatterns-11.pdf
10/32
LearningtheBridgePa1ern:DerivingIt Step:findoutwhatvariesandencapsulateit.
Step2:Representthevaria7ons.
10
7/29/2019 designPatterns-11.pdf
11/32
LearningtheBridgePa1ern:DerivingIt Step3.Tietheclassestogether
Whatuseswhat?
11
7/29/2019 designPatterns-11.pdf
12/32
LearningtheBridgePa1ern:DerivingIt Expandingthedesign
12
7/29/2019 designPatterns-11.pdf
13/32
Separa7onof
abstrac7onandimplementa7on
Separate the abstraction class hierarchy from theimplementation class hierarchy and use delegation as abridge between the two.
13
7/29/2019 designPatterns-11.pdf
14/32
ClassDiagram GenericstructureoftheBridgepa1ern
14
7/29/2019 designPatterns-11.pdf
15/32
ThePar7cipants
Abstraction defines the abstractions interface
RefinedAbstraction extends the interface defined byAbstraction
Implementor defines the interface for implementationclasses; can be different from Abstraction interface.Typically, Implementor provides only primitive operations,and Abstraction defines higher-level operations based onthese primitives.
ConcreteImplementor implements the Implementorinterface and defines its concrete implementation.
15
7/29/2019 designPatterns-11.pdf
16/32
UsingtheBridgePa1ern TheBridgepa1ernoZenincorporatestheAdapterpa1ern
Compounddesignpa1erns Instan7a7ngtheobjectsoftheBridgepa1ern
Theobjectsrepresen7ngtheabstrac7onweregiventheirimplementa7onwhilebeinginstan7ated.
Basicstrategiesfordealingwithvaria7on: Findwhatvariesandencapsulateit. Favoraggrega7onoverinheritance.
16
7/29/2019 designPatterns-11.pdf
17/32
Applicability
Usethebridgewhen: Youwanttoavoidapermanentbindingbetweenan
abstrac7onanditsimplementa7on.
Boththeabstrac7onsandtheirimplementa7onsshouldbeextensiblebysubclassing. Changesintheimplementa7onofanabstrac7on
shouldhavenoimpactonclients(i.e.codeshouldnot
havetoberecompiled).
Youwanttoshareanimplementa7onamongmul7pleobjects,andwanttohidethisfromtheclient.
17
7/29/2019 designPatterns-11.pdf
18/32
BenefitsinusingBridgePa1ern
Decouplingabstrac7onfromimplementa7on Reduc7oninthenumberofsubclasses. CleanercodeandReduc7oninexecutablesize. Interfaceandimplementa7oncanbevariedindependently.
Abstrac7onandimplementa7oncanbeextendedindependently.
Looselycoupledclientcode.
18
7/29/2019 designPatterns-11.pdf
19/32
BridgeandAdapter
TheBridgepa1ernisdesignedtoseparateaclasssinterfacefromitsimplementa7on,sothatyoucanvaryorreplacetheimplementa7onwithoutchangingtheclientcode.
AdaptermakesthingsworkaZertheyredesigned;Bridgemakesthemworkbeforetheyare.
Bridgeisdesignedup-fronttolettheabstrac7onandtheimplementa7onvaryindependently.Adapterisretrofi1edto
makeunrelatedclassesworktogether.
19
7/29/2019 designPatterns-11.pdf
20/32
BridgeandStrategy
OZen,theStrategyPa1ernisconfusedwiththeBridgePa1ern.
Eventhough,thesetwopa1ernsaresimilarinstructure,theyaretryingtosolvetwodifferentdesignproblems.
Strategyismainlyconcernedinencapsula7ngalgorithms,whereasBridgedecouplesthe
abstrac7onfromtheimplementa7on,toprovidedifferentimplementa7onforthesameabstrac7on.
20
7/29/2019 designPatterns-11.pdf
21/32
TheAbstractFactorypa1erncanbeusedbytheBridgepa1erntodecidewhich
implementa7onclasstoinstan7ateforanabstrac7onobject.
BridgeandAbstractFactory
21
7/29/2019 designPatterns-11.pdf
22/32
Flyweight
22
7/29/2019 designPatterns-11.pdf
23/32
Problemofredundantobjects
Flyweight:aclassthathasonlyoneinstanceforeachuniquestate
problem:existenceofredundantobjectscanbogdownsystem
manyobjectshavesamestate example:Fileobjectsthatrepresentthesamefileondisk
newFile("mobydick.txt") newFile("mobydick.txt") newFile("mobydick.txt")...
newFile("notes.txt") newFile("notes.txt")
23
7/29/2019 designPatterns-11.pdf
24/32
Flyweightpa1ern
flyweight:anassurancethatnomorethanoneinstanceofaclasswillhaveiden7calstate
achievedbycachingiden7calinstancesofobjectstoreduceobjectconstruc7on
similartosingleton,buthasmanyinstances,oneforeachunique-stateobject usefulforcaseswhentherearemanyinstancesofatypebutmanyarethesame
canbeusedinconjunc7onwithFactorypa1erntocreateaveryefficientobject-builder
24
7/29/2019 designPatterns-11.pdf
25/32
FlyweightandStrings
Flyweightedstrings JavaStringsareflyweightedbythecompilerwherever
possible
canbeflyweightedatrun7mewiththeinternmethodpublic class StringTest {public static void main(String[] args) {
String fly = "fly", weight = "weight";String fly2 = "fly", weight2 = "weight";
System.out.println(fly == fly2); // trueSystem.out.println(weight == weight2); // true
String distinctString = fly + weight;System.out.println(distinctString == "flyweight"); // false
String flyweight = (fly + weight).intern();System.out.println(flyweight == "flyweight"); // true
}}
25
7/29/2019 designPatterns-11.pdf
26/32
Implemen7ngaFlyweight
flyweigh7ngworksbeston immutableobjects immutable:cannotbechangedonceconstructed
classpseudo-codesketch:
publicclassFlyweighted{
sta7cmaportableofinstances
privateconstructor
sta7cmethodtogetaninstance
ifwehavecreatedthistypeofinstancebefore,getitfrommapandreturnit
otherwise,makethenewinstance,storeandreturnit
}
26
7/29/2019 designPatterns-11.pdf
27/32
27
Flyweightsequencediagram
27
7/29/2019 designPatterns-11.pdf
28/32
Classbeforeflyweigh7ng
Aclasstobeflyweightedpublic class Point {
private int x, y;
public Point(int x, int y) {this.x = x; this.y = y;
}
public int getX() { return this.x; }
public int getY() { return this.y; }
public String toString() {
return "(" + this.x + ", " + this.y + ")";
}
}
28
7/29/2019 designPatterns-11.pdf
29/32
ClassaZerflyweigh7ng
Aclassthathasbeenflyweighted!public class Point {
private static Map instances = new HashMap();
public static Point getInstance(int x, int y) {String key = x + ", " + y;if (instances.containsKey(key)) // re-use
existing pt
return (Point)instances.get(key);
Point p = new Point(x, y);
instances.put(key, p);return p;
}private final int x, y; // immutable
private Point(int x, int y) {...
29
7/29/2019 designPatterns-11.pdf
30/32
GoFPa1ernsSummary
Crea3onalPa7ernsabstracttheinstan7a7onprocess.Theyhelpmakeasystemindependentofhowitsobjectsare
created,composed,andrepresented.
StructuralPa7ernsareconcernedwithhowclassesandobjectsarecomposedtoformlargerstructures.
BehavioralPa7ernsareconcernedwithalgorithmsandtheassignmentofresponsibili7esbetweenobjects.Behavioral
pa1ernsdescribenotjustpa1ernsofobjectsorclassesbut
alsothepa1ernsofcommunica7onbetweenthem.
30
7/29/2019 designPatterns-11.pdf
31/32
DesignSpaceforGoFPa1erns
Scope: domain over which a pattern appliesPurpose: reflects what a pattern does
31
7/29/2019 designPatterns-11.pdf
32/32
GoFPa1ernRela7onships
32