Design Patterns Gang Qian Department of Computer Science University of Central Oklahoma.

Slides:



Advertisements
Similar presentations
Singleton vs utility class  at first glance, the singleton pattern does not seem to offer any advantages to using a utility class  i.e., a utility class.
Advertisements

Mutability SWE 332 Fall 2011 Paul Ammann. SWE 3322 Data Abstraction Operation Categories Creators Create objects of a data abstraction Producers Create.
COMPSCI 105 S Principles of Computer Science 12 Abstract Data Type.
Matt Klein. Decorator Pattern  Intent  Attach Additional responsibilities to an object by dynamically. Decorators provide a flexible alternative to.
Chapter 10 THINKING IN OBJECTS 1 Object Oriented programming Instructor: Dr. Essam H. Houssein.
The Bridge Pattern.. Intent Decouple an abstraction from its implementation so that the two can vary independently Also known as: Handle/Body.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Sets and Maps Chapter 9. Chapter 9: Sets and Maps2 Chapter Objectives To understand the Java Map and Set interfaces and how to use them To learn about.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
The Composite Pattern.. Composite Pattern Intent –Compose objects into tree structures to represent part-whole hierarchies. –Composite lets clients treat.
Design Patterns Module Name - Object Oriented Modeling By Archana Munnangi S R Kumar Utkarsh Batwal ( ) ( ) ( )
CERN – European Organization for Nuclear Research GS Department – Administrative Information Services Design Patterns in Groovy Nicolas Décrevel Advanced.
1 An introduction to design patterns Based on material produced by John Vlissides and Douglas C. Schmidt.
Design Patterns Standardized Recurring model Fits in many location Opposite of customization Fundamental types of pattern Choose and use as desired and.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Design Patterns.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Design patterns. What is a design pattern? Christopher Alexander: «The pattern describes a problem which again and again occurs in the work, as well as.
An Introduction to Design Patterns. Introduction Promote reuse. Use the experiences of software developers. A shared library/lingo used by developers.
Abstract Factory Design Pattern making abstract things.
Design Patterns SWE 619 Software Construction Fall 2008.
Creational Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
111 © 2002, Cisco Systems, Inc. All rights reserved.
1 Computer Science 340 Software Design & Testing Inheritance.
Chapter 18 Java Collections Framework
18 April 2005CSci 210 Spring Design Patterns 1 CSci 210.
Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.
Object-Oriented Design CSC 212. Announcements This course is speeding up and we are starting new material. Please see me if you feel this is going too.
Structural Design Patterns
Design Patterns CSIS 3701: Advanced Object Oriented Programming.
Design Patterns -- Omkar. Introduction  When do we use design patterns  Uses of design patterns  Classification of design patterns  Creational design.
SWE 316: Software Design and Architecture – Dr. Khalid Aljasser Objectives Lecture 13 Creational Design Pattern SWE 316: Software Design and Architecture.
CSE 332: Design Patterns Review: Design Pattern Structure A design pattern has a name –So when someone says “Adapter” you know what they mean –So you can.
Type Abstraction SWE Spring October 05Kaushik, Ammann Substitution Principle “In any client code, if supertype object is substituted.
Proxy.
DESIGN PATTERNS COMMONLY USED PATTERNS What is a design pattern ? Defining certain rules to tackle a particular kind of problem in software development.
Behavioral Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Software Design Patterns Curtsy: Fahad Hassan (TxLabs)
Object-Oriented Programming Chapter Chapter
 Objects versus Class  Three main concepts of OOP ◦ Encapsulation ◦ Inheritance ◦ Polymorphism  Method ◦ Parameterized ◦ Value-Returning.
Design Patterns Introduction
Design Patterns SE464 Derek Rayside images from NetObjectives.com & Wikipedia.
ISBN Object-Oriented Programming Chapter Chapter
C++ Inheritance Data Structures & OO Development I 1 Computer Science Dept Va Tech June 2007 © McQuain Generalization versus Abstraction Abstraction:simplify.
Data Abstraction SWE 619 Software Construction Last Modified, Spring 2009 Paul Ammann.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Iteration Abstraction SWE Software Construction Fall 2009.
Singleton Pattern. Problem Want to ensure a single instance of a class, shared by all uses throughout a program Context Need to address initialization.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Overview of Creational Patterns ©SoftMoore ConsultingSlide 1.
1 Creational Design Patterns CSC 335: Object-Oriented Programming and Design.
Sets and Maps Chapter 9. Chapter Objectives  To understand the Java Map and Set interfaces and how to use them  To learn about hash coding and its use.
Collections Dwight Deugo Nesa Matic
Type Hierarchies. Type Hieararchy Why?: Want to define family of related types. At the top of the hierarchy, a type whose spec defines behavior common.
CSCE 240 – Intro to Software Engineering Lecture 3.
CLASSIFICATION OF DESIGN PATTERNS Hladchuk Maksym.
Design Patterns Spring 2017.
EECE 310: Software Engineering
Chapter 10 Design Patterns.
Chapter 5:Design Patterns
MPCS – Advanced java Programming
Introduction to Design Patterns
How to be a Good Developer
object oriented Principles of software design
Advanced Programming Behnam Hatami Fall 2017.
Iteration Abstraction
Presentation transcript:

Design Patterns Gang Qian Department of Computer Science University of Central Oklahoma

Objectives Overview Hiding Object Creation Patterns that save space or time Bridge Pattern Procedures as Objects Composites Indirection Publish/Subscribe

What Is A Design Pattern Ways that programs are organized  Often utilizes type hierarchy Benefits  Improving performance or modifiability  Providing a vocabulary for understanding and discussing designs Problem  Increased complexity Should be used when benefits outweigh disadvantage Should always satisfy the substitution principle

Patterns That We Have Discussed Iterator pattern  Provide efficient access to elements of collection objects without revealing the rep Template pattern  Implementing concrete methods in a superclass using abstract methods Those abstract methods will be implemented in subclasses  The concrete method defines a template for how execution proceeds, while details are filled in later, when the subclasses are implemented

Hiding Object Creation Motivation:  Much OO code works based on an object’s behavior rather than the class that implements the object  However, code depends on the constructor of an implementing class to create the object  Sometimes, we want to limit the dependencies on classes Easy to replace the class No need to manually select a certain subclass to use for multiple implementations

Factory Pattern Factory pattern  Instead of using the constructor, factory methods are used to create objects of some class Example:  Iterator methods are factory methods that create generator objects. We do not use the constructor of the inner class  It is flexible since we can change the inner class at any time without affecting the using code  Figure: P does not directly depend on SetGen

Factory Class  Factory methods may be gathered together into a factory class  A factory class may provide a collection of static methods Those methods may create objects of a single type or of several different types

public class PolyProcs { /** EFFECTS: Creates the zero polynomial */ public static Poly makePoly() /** EFFECTS: If n < 0, throws NegativeExponentException; else returns the polynomial cx n */ public static Poly makePoly(int n, int c) throws NegativeExponentException }

Factory Objects  A factory class may also be used to create its own instances/objects called factory objects  The advantage is that the using code no long depends on the factory class that implements the factory methods. More flexibility can be achieved  Example in the figure: There are two different flavors of S and T that are created by Factory1 and Factory2 respectively M passes a factory object ( Factory1 and/or Factory2 ) to P which uses the Factory interface but is unaware of the subclasses of Factory

When to use a factory pattern  Useful when you want to hide the actual implementing class from the using code Example: When multiple implementations of a type are used, the factory method can choose a proper implementation for the using code There are two other design patterns that are closely related to factories

Builder pattern  A builder method not only hides the implementation choices for one or more types but also constructs a collection of objects of these types

Prototype pattern  A prototype is an object that can create other objects of its type  After a prototype is created by a module, the rest of the code calls a method of the prototype to obtain other objects of the prototype’s type  Different from clone() Newly created objects are in an initial state, not in the same state as that of the prototype

Patterns That Save Space or Time These patterns are useful for either speeding up a computation or reducing its storage requirements

Flyweight Pattern Flyweight pattern  Allows a program to reuse/share identical objects  The shared objects are called flyweights  Requires shared objects to be immutable Must avoid creating duplicate objects  So constructors cannot be used  Need a factory method, which checks a table that keeps track of existing objects

There are two possible structures In the first, the table is not accessible to the using code  The flyweight class provides a static factory method used to create flyweights  The table is maintained within the class as a static variable So the table is shared by all flyweights

/** OVERVIEW: Words are strings that provide methods to produce them in various forms. Words are immutable and for each unique string there is at most one word. */ public class Word { private static Hashtable t; // maps strings to words /** EFFECTS: Returns the word corresponding to s */ public static Word makeWord(String s) /** EFFECTS: Constructor. Creates a word from s */ private Word(String s) /** EFFECTS: Returns the string corresponding to this in the form suitable for context c */ public String mapWord(Context c)... }

The second structure allows users to access the table  Used when the table is used for other purposes, such as iterating over its elements, or when more than one table is needed  To implement: There is a table object that contains all the existing flyweights The factory method is a method of the object See an example on page 379

Entries need to be removed from the table if they are no longer in use  May use WeakReference  See a Java Text

Singleton Pattern Singleton pattern  Ensures that additional objects are not created if a type just needs a single object, called a singleton  The constructor of the type should not be accessible to using code  The EmptyIntList class is one example

public class IdentTable { /** OVERVIEW: An IdentTable is a mutable collection of identifiers; each distinct string has at most one entry in the table. There is only one IdentTable object. */ private static IdentTable t; // the singleton table public static IdentTable getTable() { if (t == null) t = new IdentTable(); return t; } private IdentTable() {... }... }

State Pattern State pattern  Supports objects whose rep changes dynamically Those objects that need to store different information in different states, or Those whose performance can be improved by changing their rep in different states  Different from multiple implementation When state changes, state pattern changes the rep of an object to a different type, while multiple implementation changes to another object with a different rep State pattern is made possible by using multiple implementation as the rep

Example: Set implementation  Use Vector for small sets  For large sets, use HashSet  Two thresholds T1 and T2 are needed When set size exceeds T1, switch to HashSet When size reduces to T2, switch back to Vector T2 < T1 to prevent unstable implementation for those sets whose size stays around T1

 A simple solution is to use Object as the rep in Set directly: Object els; // a vector or a hash set els can reference either a vector for a small set or a hash set for a large set Disadvantage: Code of each method needs to determine the current state and then cast els accordingly if (els instanceof Vector ) { Vector v = (Vector )els; // process v } else { HashSet t = (HashSet )els; // process t }  Both inconvenient and expensive

The state pattern offers a better solution by separating the type being implemented from the type used to implement it  The implemented type is called context  The implementing type is called state type Example: Set  Context: Set  State types: SetState, SmallSet, BigSet

Notes:  With the state pattern, context type does not need to determine the type of els using instanceof More efficient  The context is not in the hierarchy of state types. So they can have different methods  The place to switch to a different state type is set in the code of the context type We may also do this in the state type. Not good, since it requires the state type to use the context type, adding unnecessary dependency  The state pattern obviously increases programming complexity. Use it only when there is a significant benefit

More notes: State pattern can only be used for mutable types? Multiple implementations can be used for both mutable and immutable types  But it seems that, if multiple implementation is to be used directly by the using code, then it is more suitable for immutable types.  For mutable types, it seems that multiple implementation is more suitable as the state types, i.e., implementing classes

Bridge Pattern Motivation  Type hierarchy used to extend behavior can interfere with multiple implementations if they share the same superclass  Example 1: Need to create ExtendedPoly as a subtype of Poly. The new subtype ExtendedPoly adds more behaviors. However, SparsePoly and DensePoly have already been created as subtypes of Poly for multiple implementation We will need to implement ExtendedPoly with SparsePoly and DensePoly too  Not good since SparsePoly and DensePoly do not need to have the extended methods of ExtendedPoly

Example 2:  Set, BigSet, SmallSet  Now need to add ExtendedSet To solve the problem, we can separate the implementation hierarchy from the type family

Bridge pattern  Uses two different type hierarchies that has a relationship (a bridge) Notes:  The bridge pattern occurs naturally when the state pattern is used  It can also be used when a super type has both multiple implementations and extension subtypes  It adds complexity so use it only when necessary