CS 635: Advanced Object-Oriented Design & Programming |
---|
References | slide # 1 |
Motivating Creational Patterns | slide # 2 |
class ApplicationClass { Widget a; Widget b; public appMethod1() { Widget d = new Widget(); d.widgetMethod1(); blah; Widget e = new Widget(); blah; } public appMethod2() { blah; Widget f = new Widget(); f.widgetMethod1(); more blah; Widget g = new Widget(); blah; } etc.
Variation We can modify the internal Widget code without modifying the ApplicationClass
What happens when we discover a new widget and would like to use in the ApplicationClass?
Note this is a hokey professor example, in a reality variations of a Widget may be handled by parameters to a single Widget class, not by subclassing it.
Widget and ApplicationClass are coupled in several ways
class ApplicationClass { AbstractWidget a; AbstractWidget b; public appMethod1() { AbstractWidget d = new Widget(); d.widgetMethod1(); blah; AbstractWidget e = new Widget(); blah; } etc. }But we still have hard coded which widget to create!
class ApplicationClass { AbstractWidget a; AbstractWidget b; // If C+ make this a virtual function and use pointers // to ApplicationClass object public AbstractWidget createWidget() { return new Widget(); } public appMethod1() { AbstractWidget d = createWidget(); d.widgetMethod1(); blah; AbstractWidget e = createWidget(); blah; } etc. }
class ApplicationClassB extends ApplicationClass{ public AbstractWidget createWidget() { return new WidgetB(); } }Elsewhere:
ApplicationClass test = new ApplicationClassB(); test.appMethod1();
class Widget { int data; public Widget clone() { Widget aCopy = new Widget(); aCopy.data = data; return aCopy; } }Using Clone method
Widget original = new Widget(); Widget anIndependentCopy = original.clone();
class ApplicationClass { AbstractWidget a; AbstractWidget b; AbstractWidget prototype; public ApplicationClass(AbstractWidget cloneMe ) { prototype = cloneMe; } public appMethod1() { AbstractWidget d = prototype.clone(); d.widgetMethod1(); blah; AbstractWidget e = prototype.clone(); blah; } etc. }Elsewhere:
ApplicationClass test = new ApplicationClass( new Widget() ); ApplicationClass testB = new ApplicationClass( new WidgetB() );More Variation
Each one of theses are separate classes and each one has subclasses
Further assume that there are restrictions on what type of Widget can be used with which type of Cog, etc.
Factory methods or Prototypes can handle Widgets,
Cogs, Wheels, Gaskets, Gears, Gismos, ThingABobs, and
Gadgets, but it get hard to insure the wrong types of
items are not used together
class ApplicationClass { AbstractWidget a; AbstractCog b; AbstractFactory partFactory; public ApplicationClass(AbstractFactory aFactory) { partFactory = aFactory; } public appMethod1() { AbstractWidget d = partFactory.makeWidget(); d.widgetMethod1(); blah; AbstractCog e = partFactory.makeCog(); } etc.