CREATIONAL PATTERNS - University Of Colorado Boulder

2y ago
2 Views
1 Downloads
4.06 MB
38 Pages
Last View : 28d ago
Last Download : 3m ago
Upload by : Abby Duckworth
Transcription

CREATIONAL PATTERNSCSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGNLECTURE 25 — 04/12/2011 Kenneth M. Anderson, 2011Wednesday, April 13, 20111

Goals of the LectureCover material from Chapters 20-22 of the TextbookLessons from Design Patterns: FactoriesSingleton PatternObject Pool Pattern Kenneth M. Anderson, 2011Wednesday, April 13, 20112

Pattern ClassificationThe Gang of Four classified patterns in three waysThe behavioral patterns are used to manage variationin behaviors (think Strategy pattern)The structural patterns are useful to integrate existingcod into new object-oriented designs (think Bridge)The creational patterns are used to create objectsAbstract Factory, Builder, FactoryMethod, Prototype & Singleton Kenneth M. Anderson, 2011Wednesday, April 13, 20113

Factories & Their Role in OO DesignIt is important to manage the creation of objectsCode that mixes object creation with the use ofobjects can become quickly non-cohesiveA system may have to deal with a variety of differentcontexts with each context requiring a different set ofobjectsIn design patterns, the context determines whichconcrete implementations need to be present Kenneth M. Anderson, 2011Wednesday, April 13, 20114

Factories & Their Role in OO DesignThe code to determine the current context and thuswhich objects to instantiate can become complexwith many different conditional statementsIf you mix this type of code with the use of theinstantiated objects, your code becomes clutteredoften the use scenarios can happen in a few lines ofcode; if combined with creational code, the operationalcode gets buried behind the creational code Kenneth M. Anderson, 2011Wednesday, April 13, 20115

Factories provide CohesionThe use of factories can address these issuesThe conditional code can be hidden within thempass in the parameters associated with the currentcontextand get back the objects you need for the situationThen use those objects to get your work doneFactories concern themselves just with creation lettingyour code focus on other things Kenneth M. Anderson, 2011Wednesday, April 13, 20116

The Object Creation/Management RuleThis discussion brings us to this general design ruleAn object should either make and/or manage otherobjectsORit should use other objectsBUTit should never do both Kenneth M. Anderson, 2011Wednesday, April 13, 20117

Discussion (I)This rule is a guideline not an absoluteThe latter is too difficult; think of iOS view controllersThey exist to create a view and then respond torequests related to that view (which may involvemaking queries on the view)This violates the rule, strictly speaking, as it bothcreates AND uses its associated viewBut it is primarily a creational pattern within iOS Kenneth M. Anderson, 2011Wednesday, April 13, 20118

Discussion (II)But as a guideline, the rule is usefulLook for ways to separate out the creation of objectsfrom the code that make use of those objectsencapsulate the creation process and you canchange it as needed without impacting the code thatthen uses those objectsThe book demonstrates the advantages of the rulewith the following two diagrams Kenneth M. Anderson, 2011Wednesday, April 13, 20119

The perspective of a client objectInterface orAbstract ClassClient ObjectClient knows nothingabout these classesConcreteClass AClient knowsabout this classConcreteClass BThe client is completely shielded from the concreteclasses and only changes if the abstract interface changes Kenneth M. Anderson, 2011Wednesday, April 13, 201110

The perspective of a factory objectFactory Object«references»Interface orAbstract ClassFactory knows thename of this classbut not how to use it«creates»«creates»Factory knows how andwhen to create instancesof these classesConcreteClass AConcreteClass BThe factory knows nothing about how to use the abstractinterface; it just creates the objects that implement it Kenneth M. Anderson, 2011Wednesday, April 13, 201111

Factories help to limit changeIf a change request relates to the creation of an object, thechange will likely occur in a factoryall client code will remain unaffectedIf a change request does not relate to the creation ofobjects, the change will likely occur in the use of an objector the features it providesyour factories can be ignored as you work toimplement the change Kenneth M. Anderson, 2011Wednesday, April 13, 201112

Abstract Factory and Factory MethodWe’ve already seen several factory patternsFactory Method: Pizza and Pizza Store exampleHave client code use an abstract method thatreturns a needed instance of an interfaceHave a subclass implementation determine theconcrete implementation that is returnedAbstract Factory: Pizza Ingredients ExamplePattern that creates groups of related objects Kenneth M. Anderson, 2011Wednesday, April 13, 201113

Singleton PatternUsed to ensure that only one instance of a particular classever gets created and that there is just one (global) way togain access to that instanceLet’s derive this pattern by starting with a class that has norestrictions on who can create it Kenneth M. Anderson, 2011Wednesday, April 13, 201114

Deriving Singleton (I)public class Ball {private String color;public Ball(String color) { this.color color; }public void bounce() { System.out.println(“boing!”); }}Ball b1 new Ball(“red”); Ball b2 new Ball(“green”);b1.bounce(); b2.bounce(); Kenneth M. Anderson, 2011Wednesday, April 13, 201115

Problem: Universal InstantiationAs long as a client object “knows about” the name of theclass Ball, it can create instances of BallBall b1 new Ball(“orange”);This is because the constructor is public. We can stopunauthorized creation of Ball instances by making theconstructor private Kenneth M. Anderson, 2011Wednesday, April 13, 201116

Deriving Singleton (II)public class Ball {private String color;private Ball(String color) { this.color color; }public void bounce() { System.out.println(“boing!”); }}// next line now impossible by any method outside of BallBall b1 new Ball(“red”); Kenneth M. Anderson, 2011Wednesday, April 13, 201117

Problem: No Point of Access!Now that the constructor is private, no class can gain accessto instances of BallBut our requirements were that there would be at leastone way to get access to an instance of BallWe need a method to return an instance of BallBut since there is no way to get access to an instance ofBall, the method can NOT be an instance methodThis means it needs to be a class method, aka static Kenneth M. Anderson, 2011Wednesday, April 13, 201118

Deriving Singleton (III)public class Ball {private String color;private Ball(String color) { this.color color; }public void bounce() { System.out.println(“boing!”); }public static Ball getInstance(String color) {return new Ball(color);}} Kenneth M. Anderson, 2011Wednesday, April 13, 201119

Problem: Back to Universal InstantiationWe are back to the problem where any client can create aninstance of Ball; instead of saying this:Ball b1 new Ball(“blue”);they just sayBall b1 Ball.getInstance(“blue”);Need to ensure only one instance is ever createdNeed a static variable to store that instanceNo instance variables are available in static methods Kenneth M. Anderson, 2011Wednesday, April 13, 201120

Deriving Singleton (IV)public class Ball {private static Ball ball;private String color;private Ball(String color) { this.color color; }public void bounce() { System.out.println(“boing!”); }public static Ball getInstance(String color) {return ball;}} Kenneth M. Anderson, 2011Wednesday, April 13, 201121

Problem: No instance!Now the getInstance method returns null each time it iscalledNeed to check instance variable to see if it is nullIf so, create an instanceOtherwise return the single instance Kenneth M. Anderson, 2011Wednesday, April 13, 201122

Deriving Singleton (V)public class Ball {private static Ball ball;private Ball(String color) { this.color color; }public static Ball getInstance(String color) {if (ball null) { ball new Ball(color); }return ball;}} Kenneth M. Anderson, 2011Wednesday, April 13, 201123

Problem: First Parameter WinsThe previous code shows the Singleton patternprivate constructorprivate static instance variable to store instancepublic static method to gain access to instancecreates object if needed; returns itBut this code ignores the fact that a parameter is beingpassed in; so if a “red” ball is created all subsequentrequests for a “green” ball are ignored Kenneth M. Anderson, 2011Wednesday, April 13, 201124

Solution: Use a MapThe solution to the final problem is to change the private staticinstance variable to a Mapprivate Map String, Ball toybox new HashMap Then check if the map contains an instance for a given value ofthe parameterthis ensures that only one ball of a given color is evercreatedthis is an acceptable variation of the Singleton patternDEMO Kenneth M. Anderson, 2011Wednesday, April 13, 201125

Singleton Pattern: StructureSingletonstatic my instance : Singletonstatic getInstance() : Singletonprivate Singleton()Singleton involves only a single class (nottypically called Singleton). That class is afull-fledged class with other attributesand methods (not shown)The class has a static variable that pointsat a single instance of the class.The class has a private constructor (toprevent other code from instantiating theclass) and a static method that providesaccess to the single instance26Wednesday, April 13, 2011

World’s Smallest Java-based Singleton Class1 public class Singleton {23private static Singleton uniqueInstance;45private Singleton() {}67public static Singleton getInstance() {8if (uniqueInstance null) {9uniqueInstance new Singleton();10}11return uniqueInstance;12}13 }14Meets Requirements: static var, static method, private constructorExample source has this class in ken/smallest augmented with test code27Wednesday, April 13, 2011

Thread Safe? The Java code just shown is not thread safe This means that it is possible for two threads to attempt to create thesingleton for the first time simultaneously If both threads check to see if the static variable is empty at the sametime, they will both proceed to creating an instance and you will end upwith two instances of the singleton object (not good!) Example Next Slide28Wednesday, April 13, 2011

Program to Test Thread Safety1 public class Creator implements Runnable {23private int id;45public Creator(int id) {6this.id id;7}89public void run() {10try {11Thread.sleep(200L);12} catch (Exception e) {13}14Singleton s Singleton.getInstance();15System.out.println("s" id " " s);16}1718public static void main(String[] args) {19Thread[] creators new Thread[10];20for (int i 0; i 10; i ) {21creators[i] new Thread(new Creator(i));22}23for (int i 0; i 10; i ) {24creators[i].start();25}26}2728 }29Wednesday, April 13, 2011Creates a “runnable” objectthat can be assigned to athread.When its run, its sleeps for ashort time, gets an instance ofthe Singleton, and prints outits object id.The main routine, creates tenrunnable objects, assignsthem to ten threads and startseach of the threads29

Output for Non Thread-Safe Singleton Code s9 Singleton@45d068s8 Singleton@45d068s3 Singleton@45d068s6 Singleton@45d068s1 Singleton@45d068s0 Singleton@ab50cds5 Singleton@45d068s4 Singleton@45d068s7 Singleton@45d068s2 Singleton@45d068Whoops!Thread 0 created an instance of the Singleton class at memory locationab50cd at the same time that another thread (we don’t know which one)created an additional instance of Singleton at memory location 45d068!30Wednesday, April 13, 2011

How to Fix?1 public class Singleton {2private static Singleton uniqueInstance;34private Singleton() {}56public static synchronized Singleton getInstance() {7if (uniqueInstance null) {8uniqueInstance new Singleton();9}10return uniqueInstance;11}121314 }15In Java, the easiest fix is to add the synchronized keyword to thegetInstance() method.31Wednesday, April 13, 2011

Object PoolA variant of the Singleton Pattern is known as the ObjectPool patternThis allows some instances (x) of an object to becreated up to some maximum number (m)where 1 x mIn this case, each instance provides a reusable service(typically tied to system resources such as networkconnections, printers, etc.) and clients don’t care whichinstance they receive Kenneth M. Anderson, 2011Wednesday, April 13, 201132

Object Pool Structure DiagramClient*Pool- Pool() getInstance() : Pool acquireReusable() : Reusable releaseReusable(Reusable)Reusable Kenneth M. Anderson, 2011Wednesday, April 13, 201133

Common Use: Thread PoolOne place in which the Object Pool pattern is usedfrequently is in multithreaded applicationswhere each thread is a “computation resource” thatcan be used to execute one or more tasks associatedwith the systemwhen a task needs to be done, a thread is pulled out ofthe pool and assigned the task; it executes the task andis then released back to the pool to (eventually) workon other tasks Kenneth M. Anderson, 2011Wednesday, April 13, 201134

Examples (1)First, a “homegrown” exampleThreadPool implemented as a blocking queue of Threadsubclasses called ProcessorsGoal is to calculate the number of primes between 1 and20M (20,000,000).Producer creates tasks to calculate primes between a subsetof numbers, say 1 to 250,000; 250,001 to Processor calculates in separate threadConsumer joins with Processors and merges the results Kenneth M. Anderson, 2011Wednesday, April 13, 201135

Examples (2)An example that makes use of a thread pool provided by theJava Concurrency API (example taken from this excellent book)The class that implements the object pool pattern is knownas an ExecutorServiceYou pass it instances of a class called CallableIt returns instances of a class called FutureYou hold onto the Future object while Callableexecutes in the backgroundthen retrieve Callable’s result from the Future object Kenneth M. Anderson, 2011Wednesday, April 13, 201136

Wrapping UpLooked atthe use of Factories in OO Designthe Singleton and Object Pool Design Patternssaw example of thread-safe singletonssaw use of thread pools in java.util.concurrent Kenneth M. Anderson, 2011Wednesday, April 13, 201137

Coming Up NextLecture 25: More PatternsLecture 26: Textbook Wrap UpHomework 8 Due on FridayHomework 9 Assigned on FridayFinal Homework of the Class Kenneth M. Anderson, 2011Wednesday, April 13, 201138

The Gang of Four classified patterns in three ways The behavioral patterns are used to manage variation in behaviors (think Strategy pattern) The structural patterns are useful to integrate existing cod into new object-oriented designs (think Bridge) The creational patterns are us

Related Documents:

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

Greatest advantage of patterns: allows easy CHANGEof applications (the secret word in all applications is "CHANGE"). 3 Different technologies have their own patterns: GUI patterns, Servlet patterns, etc. (c) Paul Fodor & O'Reilly Media Common Design Patterns 4 Factory Singleton Builder Prototype Decorator Adapter Facade Flyweight Bridge

design patterns: J2EE design patterns. S.N. Pattern & Description 1 Creational Patterns These design patterns provides way to create objects while hiding the creation logic, rather than instantiating objects directly using new operator. This gives program more flexibility in deciding which objects need to be created for a given use case. 2

There are different types and levels of design patterns. For example, the MVC is the architectural level of design pattern while the rest of the patterns from the list above are component level design patterns. The basic types are Behavior, Creational, Structural, and System design patterns. Names are extremely important in design .

3 Type of Design Patterns Erich Gamma, Richard Helm, Ralph Johnson and John Vlisides in their Design Patterns book define 23 design patterns divided into three types: Creational patterns are ones that create objects for you, rather than having you instantiate objects directly. This gives your

LLinear Patterns: Representing Linear Functionsinear Patterns: Representing Linear Functions 1. What patterns do you see in this train? Describe as What patterns do you see in this train? Describe as mmany patterns as you can find.any patterns as you can find. 1. Use these patterns to create the next two figures in Use these patterns to .

God blessed the man and woman Told them to be fruitful, multiply and fill the earth This is the “Creational Mandate” 1. Be fruitful 2. Multiply 3. Fill the earth 4. Subdue it (military term) 5. Have dominion/rulership God’s creational intention Firstly God created Man – male and female, He created them in

Studying the Korean language is even more challenging and fascinating than studying other languages. Korea has an ancient culture. Over the centuries, it has— amazingly—been able to mix all the influences coming from Central Asia, the Steppes, Manchuria, China, Japan, and the West into a beautiful, brilliant, and unique new culture. This cultural richness has affected the Korean language .