Presentation is loading. Please wait.

Presentation is loading. Please wait.

Design Patterns Based on slides provided by Abbie Jarrett

Similar presentations


Presentation on theme: "Design Patterns Based on slides provided by Abbie Jarrett"— Presentation transcript:

1 Design Patterns Based on slides provided by Abbie Jarrett
with additional input from Chris Bohn

2 Our plan What is a Design Pattern? Why Design Patterns?
Design Patterns Vs. Architecture Elements of a Design Pattern Types of Design Patterns Catalog of Common Designs Examples In Practice Example

3 "Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice” – Christopher Alexander, A Pattern Language, 1977

4 What is a Design Pattern?
Design Patterns are descriptions of communicating objects and classes. The patterns are abstract, but designers then customize them to solve general design problems in particular contexts. They reflect a common problem and solution Expressed in terms of classes/objects and interfaces Class/object interactions that programmers have found useful

5 Benefits of Design Patterns
Shared language of design Increased understanding across developers Reaches wider audience Learn from others experience – Designing is difficult! Tested solutions to common problems Known tradeoffs What problems a design will be a solution for

6 Languages commonly used
Geared towards Object Oriented Programming languages Not exclusive, but OOP make implementation easier Examples: Java, C#, C++, etc. Can be implemented in every language

7 Architecture Vs. Design Patterns
Design patterns bridge the gap between system architecture and code. Design patterns help explain how some of your classes will be laid out in order to increase readability, maintainability, reliability and performance. ARCHITECTURE DESIGN CODE IMPLEMENTATION

8 Elements of a Design Pattern
Name Increases universal understanding Problem When to apply the pattern (motivation) Solution Design elements and their relationships Consequences Trade-offs in using the pattern

9 Types of Design Patterns
Behavioral Patterns Characterizes the ways in which classes or objects interact and distributes responsibility Structural Patterns Represents how classes and objects are combined to create larger structures (composition of objects) Creational Patterns Concerned with the creation of objects or classes

10 Behavioral Patterns Assist and facilitate the relationship and interaction between objects to be loosely coupled. The goal is to increase flexibility in carrying out communication, and to assign responsibilities and encapsulate behavior in specific classes

11 Behavioral Patterns Iterator: Access elements of an object sequentially without exposing the underlying representation Command: Create objects that encapsulate actions and parameters Chain of responsibility: Delegate commands to a chain of processing objects State: Allow an object to alter its behavior when its internal state changes Observer: publish/subscribe patterns that allow a number of observer objects to see an event

12 Iterator Problem: We want to access elements of an aggregate object sequentially without exposing its underlying implementation Solution: Create abstract Iterator and Aggregate classes Create concrete Aggregate and Iterator classes The Aggregate class creates its own (appropriate) Iterator Consequences: Supports a variety of traversal types of collections Simplifies the interface to the collection Supports simultaneous traversals of varying types

13 Iterator abstract class i inheritance instantiation concrete class
Aggregate Iterator abstract class CreateIterator() CreateIterator() inheritance instantiation ConcreteAggregate concrete class ConcreteIterator CreateIterator() delegation implementation return new ConcreteIterator(ths)

14 Iterator EXAMPLE return new Iterator

15 Structural Patterns How classes and objects are composed to form larger structures Identify the structure by identifying the relationships between classes How classes inherit from each other How they are composed from other classes

16 Structural Patterns Façade: Provides a simplified interface to a large body of code Adapter: Creates a wrapper around an already existing class to allow two incompatible interfaces to work together Bridge: Decouples an abstraction from its implementation so the two can vary independently Decorator: dynamically adds or overrides behavior in an existing method of an object

17 Façade Problem: We want to create a high-level interface to hide complexity of sub-classes Solution: Create an overarching interface Create classes that will use your interface Create a façade class that will create your correct object Consequences Provides a simple default view of the sub-system that is good enough for most clients Lessens coupling between subsystem and clients Hides the complexities of the subsystems

18 Façade Facade Facade

19 Façade EXAMPLE

20 Example classes and interfaces
public class Square implements Shape { @Override public void draw() System.out.println("Square::draw()"); } public interface Shape { void draw(); } public interface Shape { void draw(); } public class Circle implements Shape { @Override public void draw() System.out.println("Circle::draw()"); } public class Rectangle implements Shape { @Override public void draw() System.out.println("Rectangle::draw()"); } public class Rectangle implements Shape { @Override public void draw() System.out.println("Rectangle::draw()"); }

21 public class ShapeMaker { private Shape circle;
private Shape rectangle; private Shape square; public ShapeMaker() circle = new Circle(); rectangle = new Rectangle(); square = new Square(); } public void drawCircle() circle.draw(); public void drawRectangle() rectangle.draw(); public void drawSquare() square.draw(); public class FacadePatternDemo { public static void main(String[] args) ShapeMaker shapeMaker = new ShapeMaker(); shapeMaker.drawCircle(); shapeMaker.drawRectangle(); shapeMaker.drawSquare(); } Circle::draw() Rectangle::draw() Square::draw() Example: /

22 Creational PatternS Implemented when a decision must be made at the time of instantiation of a class. Used when basic form of object creation could result in design problems or increase complexity; lets you hide details on how instances of classes are created and put together. Ex: Creating an object Student student = new Student();

23 Creational Patterns Factory Method: creates objects without specifying the exact class to create (subclasses decide which to instantiate) Abstract Factory: an abstract class creates objects without specifying a concrete sub-class Builder: Creates complex objects while separating construction and representation Prototype: Creates objects by cloning an existing object Singleton: Restricts object creation for a class to a single instance

24 Singleton Problem: We want a class to be limited to one instance
Ex: Window Manager, Logger Solution: Create one object and reuse it Make constructor private or protected; limit its use to one. Provide static method or fields to allow access to the only instance of the class Consequences Class encapsulates code; no burden to client Class can be subclassed if constructor is protected

25 Singleton return uniqueInstance

26 Singleton EXAMPLE public class Board { private static Board instance;
public static Board getBoard() { if( instance == null ) instance = new Board(); return instance; } private Board() {…}

27 Additional Examples Observer (Behavioral) Decorator (Structural) Factory Method (Creational)

28 Observer We want dependent class’ states to be consistent with a master’s state – implies a one-to many relationship between objects Solution: There is an Observer and a Subject An abstract Observer will have different types of observers implementing this class Defines protocol for updating dependent classes A concrete Subject class will use the observer class Consequences: Loosely coupled design between objects Subject is unaware of observers

29 Observer

30 Observer ExampLE ©2000 Christopher A. Bohn

31 Decorator Problem: We want to add responsibilities to objects dynamically without sub-classing Solution: Create a wrapper for your class Interface of wrapper conforms to interface of class; it forwards requests to the class transparently, but may add other actions. Abstract Decorator provides common interface Consequences Keeps root classes simple and fewer in number Proliferation of run-time instances Can be complicated to implement

32 Decorator EXAMPLE

33 Factory METHOD Problem: we want to define an interface for creating an object, but let subclasses decide which class to instantiate. Solution: Ask Factory for a new object instead Create an ObjectFactory class with methods like createObject(int objectID) The factory will generate the correct type of object Consequences Each factory must be initialized before using it The factory may perform additional operations More difficult to implement . You could also pass in a ‘state’ enum or some other determining factor

34 Factory METHOD the carrier and any carrier specific fields.

35 Factory METHOD eXAMPLE
Chef {abstract} cook() getCookbook() {abstract} book : Cookbook Cookbook {abstract} book = getCookbook() return new FrenchCookbook() FrenchChef getCookbook() FrenchCookbook ItalianChef getCookbook() ItalianCookbook return new ItalianCookbook()

36 In Practice Suppose we are creating a system that will read in coordinate pairs of different people from a file. Because these are some important people, the files may be zipped, encrypted or both zipped and encrypted. Using these coordinate pairs, we will need to make an API Call to determine the distance between the person’s current location and previous location. If the person traveled less than 50 miles we will create a no-threat object, if they traveled 100 we will mark them as a potential threat and if they traveled 200, we will create a threat object. Now, we need to update our database with the new information, notify a distance tracker and send updates to the President. In order to create this system, what design patterns should we consider implementing?                                                    

37 In Practice We are creating a system that will read in coordinate pairs of different people from a file. Because these are some important people, the files may be zipped, encrypted or both zipped and encrypted. Decorator: Dynamically add functionality without changing class Using these coordinate pairs, we will need to make an API Call to determine the distance between the person’s current location and previous location. Decorator: The API functionality can shift without breaking your class If the person traveled less than 50 miles we will create a no-threat object, if they traveled 100 we will mark them as a potential threat and if they traveled 200, we will create a threat object. Factory: Hide the complexity of the object creation Now, we need to update our database with the new information, notify a distance tracker and send updates to the President. Observer: Let other objects determine if they care about the state change                                                  

38 Design Patterns: Summary
A general, repeatable solution to common software development problems. Not a finished design that can be directly transformed into code: the pattern must be instantiated as a specific design Helps prevent subtle issues that may cause major problems Improves code readability and thus maintainability for programmers and architects.

39 Recommended Design Patterns: Elements of Reusable Object-Oriented Software Authors: “Gang of four” Examples in C++

40 Recommended Design Patterns Explained: A New Perspective on Object-Oriented Design Authors: Shalloway, Trott Examples in Java

41 References Design Patterns: Introduction and Overview; Abhishek Sagi; December 2011 Design Patterns: Principles of Software System Construction; Johnathan Aldrich, Professor at Carnegie Mellon School of Computer Science; Fall 2011 Design Patterns: Adam Porter, Professor at University of Maryland; March 2005


Download ppt "Design Patterns Based on slides provided by Abbie Jarrett"

Similar presentations


Ads by Google