Download presentation
Presentation is loading. Please wait.
Published byMitchell Harvey Modified over 9 years ago
2
CS 325: Software Engineering March 19, 2015 Applying Patterns (Part B) Code Smells The Decorator Pattern The Observer Pattern The Template Method Pattern The Singleton Pattern The Object Pool Pattern The Factory Method Pattern
3
CS 325 March 19, 2015 Page 173 Code Smells Code smells are symptoms in a program that indicate that refactoring might be needed. Duplicate code Large functions Large classes Tiny classes Overdependence on the implementation details of another class Appropriate use of design patterns can help avoid code smells and facilitate refactoring for program improvement. One important concept to keep in mind is the Open-Closed Principle, which advocates designing software in such a way that it will absorb new variations without having to introduce new fundamental structure. In other words, the capabilities of a system can be extended without substantially changing the basic system.
4
CS 325 March 19, 2015 Page 174 Commonality & Variability During the design process, it is important to recognize the commonalities and the variabilities of the objects being designed. This practice is commonly handled via: Procedures: Similar code fragments should be replaced by some new function, with variabilities handled by means of parameters or custom code that is used before or after calls to the common function. Inheritance: Code common to all objects is placed in the superclass, while variabilities are placed in the subclasses. Polymorphism: Class templates implement the same operations on different types, with the variability handled by means of the template parameters.
5
CS 325 March 19, 2015 Page 175 The Decorator Pattern There are times when the use of subclasses to modify the behavior of individual objects is problematic. When objects are alike in some fundamental way, but might have a variety of distinctive details, the Decorator Pattern avoids the complexity of having a large number of derived classes. By applying a Decorator class to the base class, and allowing the Decorator class to have the needed derived classes, the base class is kept streamlined, while still affording flexibility when it comes to adding responsibilities to the base class.
6
CS 325 March 19, 2015 Page 176 The Decorator Pattern: An Example Consider the variations that might be needed in order to handle different check-in needs at a hotel. The AbstractCheckIn component has a derived class: the concrete ActualCheckIn component. The abstract CheckInDecorator class has three derived concrete Decorator subclasses: the AccessibilityCheckIn (for blindness and wheelchairs), the CommunicationCheckIn (for broadband and Internet access), and the FamilyCheckIn (for family size). Each guest’s check-in may now be “decorated” with accessibility, communication, and family features.
7
CS 325 March 19, 2015 Page 177 The Observer Pattern A large monolithic design doesn’t scale well as new requirements materialize. With the Observer pattern, a one-to-many dependency is established between objects so that when one object changes state, all of the dependent objects are notified and updated automatically. The common components are stored in a Subject abstraction, while the variable components are stored in an Observer hierarchy. The Subject is defined as the "keeper" of the shared data. Viewing functionality is delegated to decoupled and distinct Observer objects. Observers register themselves with the Subject as they are created. Whenever the Subject changes, it broadcasts that fact to all registered Observers, and each Observer queries the Subject for that subset of the Subject's state that it is responsible for monitoring.
8
CS 325 March 19, 2015 Page 178 The Observer Pattern: An Example In an auction/bidders scenario, the bidders may be viewed as observers, with the high bid as the object being viewed. The bidders are observers, receiving notification from the auctioneer whenever a new high bid is placed. The acceptance of a bid by the auctioneer results in a broadcast of the new high bid to the bidders.
9
CS 325 March 19, 2015 Page 179 The Template Method Pattern On occasion, two different algorithms have significant similarities, but demonstrate no reuse of common interface or implementation. If a change that is common to both algorithms becomes necessary, duplicate effort must be expended. Subclasses are then defined to redefine the variant steps without altering the basic algorithms’ structure. The Template Method pattern addresses this problem by setting up a skeleton algorithm containing the common steps, with the variant steps represented by default “placeholders”.
10
CS 325 March 19, 2015 Page 180 The Template Method Pattern: An Example In order to accommodate sorting in either ascending or descending order, only the element comparison techniques need to differ. When the Client sorts in ascending order, the array is processed in the common manner, the comparisons are handled by the compare operation in the SortAscending subclass, and then the array is returned in the common manner. Similarly, when the Client sorts in descending order, the array is processed in the common manner, the comparisons are handled by the compare operation in the SortDescending subclass, and then the array is returned in the common manner.
11
CS 325 March 19, 2015 Page 181 Factories Creational design patterns, known as factories, employ methods/objects to instantiate other objects. By separating the instantiation of an object from the use of that object, a software system can make use of the object without being concerned with implementation details. Rather than complicate client code with elaborate switch statements or if-else nestings in order to vary the behavior within a software system, factories enable the system to vary the object that is being used, with the appropriate behavior built into the object itself.
12
CS 325 March 19, 2015 Page 182 The Singleton Pattern There are times when an application needs one, and only one, instance of a particular object. Unfortunately, proper enforcement of that object’s uniqueness and appropriate global access to the object can be problematic. This is particularly useful when one object is needed to coordinate actions across a software system. One problem associated with this pattern is the fact that it complicates unit testing, since it introduces a global state into the software system. The Singleton pattern was developed to deal with these problems. A special method is used to instantiate objects. When this method is called, it checks to see if the object has already been instantiated. If it has, the method simply returns a reference to the object. If not, the method instantiates it and returns a reference to the new instance.
13
CS 325 March 19, 2015 Page 183 The Singleton Pattern: An Example One situation in which one (and only one) instance of a class is needed is a system administrator. The constructor is defined to be private, in order to prevent direct instantiation of objects. The public static accessor method instantiates the class if the member is null, setting its value. The private static member of the class refers to the desired object, which is initially null. In this way, the class, and not the programmer, is responsible for restricting the number of instances created.
14
CS 325 March 19, 2015 Page 184 The Object Pool Pattern When initializing a class instance is costly, the rate of initializations is high, and the number of instances in use is always low, an object pool might help. The Object Pool pattern employs a set of initialized objects that are kept ready to use, instead of being allocated and destroyed on command. These benefits are particularly true for objects like database connections, socket connections, threads, and large graphic objects (e.g., fonts, bitmaps). The pooled object is obtained in a predictable amount of time, while the creation of new objects (especially over a network) might take variable time.
15
CS 325 March 19, 2015 Page 185 The Object Pool Pattern: An Example When a connection is needed, the pool is called. If the pool is empty, a new implementation is acquired or the client will await an existing implementation to be returned to the pool; otherwise, one of the reusable implementations in the pool is used. When the connection is no longer needed, it is disposed of. This usually means release back into the pool. However, if the pool has some maximum size, then the released implementation could be destroyed.
16
CS 325 March 19, 2015 Page 186 The Factory Method Pattern At times, the behavior of objects needs to be standardized for a range of applications, but the applications need to define how to create the objects. This makes the design of the objects more customizable without resorting to new classes. Instead, this pattern defines a separate method for creating objects, letting subclasses override the derived type of product that is created. The Factory Method pattern reduces the duplication of code that would result from having separate methods in multiple classes just to perform custom object creation.
17
CS 325 March 19, 2015 Page 187 The Factory Method Pattern: An Example One framework may be used to generate multiple document types. The Document instantiates Page objects (via the CreatePage “factory method”) in a manner consistent with the particular Document subclass (Resume or Report) that has been established. Report documents will instantiate Title, Text, and Bibliography pages, while Resume documents will instantiate Skills, Education, and Experience pages.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.