Presentation is loading. Please wait.

Presentation is loading. Please wait.

9/28/01F-1 © 2001 T. Horton CS 494 Object-Oriented Analysis & Design Design Patterns.

Similar presentations


Presentation on theme: "9/28/01F-1 © 2001 T. Horton CS 494 Object-Oriented Analysis & Design Design Patterns."— Presentation transcript:

1 9/28/01F-1 © 2001 T. Horton CS 494 Object-Oriented Analysis & Design Design Patterns

2 9/28/01F-2 Readings Chapter 1 of GoF book –Especially pp. 1-10, 24-26 –I’ll get this to you (toolkit, reserve, Web?) Eckel’s Thinking in Patterns, on Web –Chap. 1, “The pattern concept” –Chap. 5, “Factories” Handouts on various patterns

3 9/28/01F-3 Idioms, Patterns, Frameworks Idiom: a small language-specific pattern or technique –A more primitive building block Design pattern: a description of a problem that reoccurs and an outline of an approach to solving that problem –Generally domain, language independent –Also, analysis patterns Framework: –A partially completed design that can be extended to solve a problem in a domain Horizontal vs. vertical

4 9/28/01F-4 Examples of C++ Idioms Use of an Init() function in constructors –If there are many constructors, make each one call a private function Init() Init() guarantees all possible attributes are initialized Initialization code in one place despite multiple constructors Don’t do real work in a constructor –Define an Open() member function Constructors just do initialization Open() called immediately after construction –Constructors can’t return errors They can throw exceptions

5 9/28/01F-5 Design Patterns: Essential Elements Pattern name –A vocabulary of patterns is beneficial Problem –When to apply the pattern, what context. –How to represent, organize components –Conditions to be met before using Solution –Design elements: relationships, responsibilities, collaborations –A template for a solution that you implement Consequences –Results and trade-offs that result from using the pattern –Needed to evaluate design alternatives

6 9/28/01F-6 Patterns Are (and Aren’t) Name and description of a proven solution to a problem Documentation of a design decision They’re not: –Reusable code, class libraries, etc. (At a higher level) –Do not require complex implementations –Always the best solution to a given situation –Simply “a good thing to do”

7 9/28/01F-7 Describing Design Patterns The GoF defined a standard format –Generally followed –Not just a UML diagram! Pattern Format (13 sections): –Pattern name and classification –Intent: what’s it do? Rationale? –Also known as –Motivation A scenario that illustrates a sample problem and how this patterns helps solve it. –Applicability For which situations can this be applied? –Structure Graphical representation (e.g. UML)

8 9/28/01F-8 Pattern Format (cont’d) –Participants Classes and objects, their responsibilities –Collaborations How participants interact –Consequences –Implementation Pitfalls, hints, techniques, language issues –Sample code Code fragments that illustrate the pattern –Known uses From real systems –Related patterns Similar patterns, collaborating patterns

9 9/28/01F-9 Example 1: Singleton Pattern Context: Only one instance of a class is created. Everything in the system that needs this class interacts with that one object. Controlling access: Make this instance accessible to all clients Solution: –The class has a static variable called theInstance (etc) –The constructor is made private (or protected) –Clients call a public operation getInstance() that returns the one instance This may construct the instance the very first time or be given an initializer

10 9/28/01F-10 Singleton: Java implementation public class MySingleton { private static MySingleton theInstance = new MySingleton(); private MySingleton() { // constructor … } public static MySingleton getInstance() { return theInstance; } }

11 9/28/01F-11 Static Factory Methods Singleton patterns uses a static factory method –Factory: something that creates an instance Advantages over a public constructor –They have names. Example: BigInteger(int, int, random) vs. BigInteger.probablePrime() –Might need more than one constructor with same/similar signatures –Can return objects of a subtype (if needed) Wrapper class example: Double d1 = Double.valueOf(“3.14”); Double d2 = new Double (“3.14”); More info: Bloch’s Effective Java

12 9/28/01F-12 The State Design Pattern A connection can be in various states –Handles requests differently depending on state Connection delegates requests to its state object –Which changes dynamically

13 9/28/01F-13

14 9/28/01F-14 Categories of Design Patterns GoF categories –Creational –Structural –Behavioral Can you classify patterns we’ve seen so far?

15 9/28/01F-15 Factories for Creating Objects Recall ideas about reducing coupling between a client and objects in an inheritance hierarchy Common approaches for achieving this –Factory pattern (AKA Factory Method pattern) A client calls a method to get a reference to an object, but only knows its interface or supertype –Abstract factory: A client gets an instance of a factory class factory object creates one particular kind of many related objects AKA kit or toolkit pattern

16 9/28/01F-16 Factory Method Pattern A factory method –Is called to create an object for the client –Returns a type that is interface or abstract class –May be implemented in several places or in one Factory class –Seeks to improve coupling, reduce dependancies Examples in Java (or are they? you decide) –toString() –Arrays.asList(obj[] ary) // returns List –iterator()

17 9/28/01F-17 Desired Framework: (From Grand’s book.) But how can Application create instances of Document objects without subclass coupling? It can’t according to this diagram. But see next slide!

18 9/28/01F-18 Solution: Use Document Factory class to create various types of documents (From Grand’s book.)

19 9/28/01F-19 Factory Method Pattern: General Structure discriminator is some parameter that indicates what kind of Product subclass to instantiate (perhaps a string). (From Grand’s book.)

20 9/28/01F-20 Another Example: Java Iterator What kind of type is Iterator? –Answer: interface How do we get an Iterator object? –Answer: from a factory method defined in the collection class Consider: List l1 = Arrays.asList(ary); Iterator i1 = l1.iterator();

21 9/28/01F-21 Abstract Factory Pattern Abstract Factory is a class –That contains a set of related factory methods for creating various types of objects (e.g. widgets) –Abstract class: all these are abstract methods –Developer writes subclass of the Abstract Factory Set of methods create related types of objects –Client instantiates one of several subclasses to get a particular kind of factory object Calls methods on that object to get instances of different widgets Factory creates only widgets of one “family”

22 9/28/01F-22 General Overview of Abstract Factory Note use of static method in factory class to return particular concrete factory object. This could be a factory method that takes a string as a discriminator. (From Grand’s book.)

23 9/28/01F-23 Example of Abstract Factory (From Grand’s book.)

24 9/28/01F-24 Benefit of Abstract Factories: substituting one factory for another. Application can be modified by swapping out the type of factory it uses. (From Martin’s ASD book.)

25 9/28/01F-25 The problem (again): If SomeApp only uses the Shape interface, it shouldn’t use new to create instances of concrete classes. •(From Martin’s ASD book.)

26 9/28/01F-26 Abstract Factory is a better Solution: SomeApp uses a particular ShapeFactory implementation (no use of new) Note here that “abstract” factory is an interface. That seems fine, but it’s not clear from this diagram how SomeApp creates instance of a concrete factory. (From Martin’s ASD book.)

27 9/28/01F-27 OO Principle: Open-Closed Principle The Open-Closed Principle (OCP) –Classes should be open for extension, but closed for modification. Don’t allow clients to alter your code. Allow clients to easily add things to your classes. –Provide means of extension Example of this: the Observer design pattern Note there’s a cost to making classes extendable

28 9/28/01F-28 Another Design Solution for This You’re doing Beverages for a coffee shop Four types of coffee-drink: –HouseBlend, DarkRoast, Decaf, Espresso Also can add (for a cost): –SteamedMilk, Soy, Mocha, WhippedMilk Want a cost() method in each class to calculate costs Question: how to structure classes for this? –Avoid class explosion. Same solution as for Customer and Accounts?

29 9/28/01F-29 One Solution Beverage abstract super-class –Subclasses: HouseBlend, DarkRoast, Decaf,… Fields / Attributes: –milk, soy, mocha, whip Methods / Operations: –hasMilk(), setMilk(); hasSoy(), setSoy(); … Issues?

30 9/28/01F-30 Problems with This Approach Price for condiments? Alter existing code New condiments? Add methods; alter cost() operation in superclass New beverage like ice tea that shouldn’t have whipped milk? Want a double mocha?

31 9/28/01F-31 Decorator Design Pattern “Decorate” an object –Wrappers: a object defined so that it encloses another object Key points: –Decorators have the same supertype as the object they wrap. So you can use a decorated object in the same place as the original object (a la Liskov) –Can use more than one decorator on an object –Can decorate objects at run-time

32 9/28/01F-32 Decorators in Java I/O Used for input and output file streams Many stream types are wrappers –Add extra functionality, e.g. push-back, line-numbering, buffering, etc. –Create by using “more basic” file-stream object in constructor –Can used a wrapped-stream where you’d use any stream See Java API: http://java.sun.com/j2se/1.4.2/docs/api/java/io/FilterInp utStream.html http://java.sun.com/j2se/1.4.2/docs/api/java/io/FilterInp utStream.html Also used in Java Swing

33 9/28/01F-33 Decorators in Java I/O FileInputStream istream = new FileInputStream(“foo.txt”); BufferedInputStream bstream = new BufferedInputStream(istream);

34 9/28/01F-34 Issues with Decorators Disadvantages: –May add many classes, makes package hard to understand Like Java I/O streams –Client code should not rely on knowing a reference’s specific concrete class May get wrapped. Wrapping intended to transparent to client code. –Creating new objects could be more complex A factory pattern class

35 9/28/01F-35 Swing Examples of Decorators Example 1: Button with a diagonal line –http://www.ideas2work.com/decorator-java.htmlhttp://www.ideas2work.com/decorator-java.html –Note: quick read, but not a lot of explanation of Swing and how buttons are drawn or components Example 2 & 3: Component border, minimize –http://www.onjava.com/pub/a/onjava/2003/02/05/decorator.html?page=1http://www.onjava.com/pub/a/onjava/2003/02/05/decorator.html?page=1 –Better explanation, especially of Decorator pattern Inheritance vs. decoration how components are composed and painted in Swing


Download ppt "9/28/01F-1 © 2001 T. Horton CS 494 Object-Oriented Analysis & Design Design Patterns."

Similar presentations


Ads by Google