Design Patterns (Part 1) Design Patterns are time-tested solutions to recurring design problems. Are the answer to a question that commonly arises “How.

Slides:



Advertisements
Similar presentations
Design Patterns.
Advertisements

What Are Design Patterns and Why Do I Need Them? Software professionals may be familiar with the term "Design Patterns," but many have no idea of where.
Welcome to. Who am I? A better way to code Design Patterns ???  What are design patterns?  How many are there?  How do I use them?  When do I use.
 Recent researches show that predicative programming can be used to specify OO concepts including classes, objects, interfaces, methods, single and multiple.
Observer Method 1. References Gamma Erich, Helm Richard, “Design Patterns: Elements of Reusable Object- Oriented Software” 2.
18-1 Verifying Object Behavior and Collaboration Role playing – the act of simulating object behavior and collaboration by acting out an object’s behaviors.
CS590L - Lecture 6 1 CS590L Distributed Component Architecture References: - E. Gamma, R. Helm, R. Johnson, J. Vlissides, Design Patterns: Elements of.
5. Design Patterns Are the answer to a question that commonly arises “How can I … ?” Patterns record successful solutions in software development for sharing.
Observer Pattern Fall 2005 OOPD John Anthony. What is a Pattern? “Each pattern describes a problem which occurs over and over again in our environment,
Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
05/26/2004www.indyjug.net1 Indy Java User’s Group June Knowledge Services, Inc.
(c) 2009 University of California, Irvine – André van der Hoek1June 13, 2015 – 21:42:16 Informatics 122 Software Design II Lecture 8 André van der Hoek.
IEG3080 Tutorial 7 Prepared by Ryan.
Design Patterns CS is not simply about programming
Design Patterns. What are design patterns? A general reusable solution to a commonly occurring problem. A description or template for how to solve a problem.
Spring 2010CS 2251 Design Patterns. Spring 2010CS 2252 What is a Design Pattern? "a general reusable solution to a commonly occurring problem in software.
(c) 2010 University of California, Irvine – André van der Hoek1June 29, 2015 – 08:55:05 Informatics 122 Software Design II Lecture 8 André van der Hoek.
PRESENTED BY SANGEETA MEHTA EECS810 UNIVERSITY OF KANSAS OCTOBER 2008 Design Patterns.
Design Patterns academy.zariba.com 1. Lecture Content 1.What are Design Patterns? 2.Creational 3.Structural 4.Behavioral 5.Architectural 6.Design Patterns.
1 An introduction to design patterns Based on material produced by John Vlissides and Douglas C. Schmidt.
Vrije Universiteit amsterdamPostacademische Cursus Informatie Technologie Idioms and Patterns polymorphism -- inheritance and delegation idioms -- realizing.
Design Patterns.
Software Design Refinement Using Design Patterns Instructor: Dr. Hany H. Ammar Dept. of Computer Science and Electrical Engineering, WVU.
05 - Patterns Intro.CSC4071 Design Patterns Designing good and reusable OO software is hard. –Mix of specific + general –Impossible to get it right the.
CSSE 374: Introduction to Gang of Four Design Patterns
An Introduction to Design Patterns. Introduction Promote reuse. Use the experiences of software developers. A shared library/lingo used by developers.
SOEN 6011 Software Engineering Processes Section SS Fall 2007 Dr Greg Butler
January 12, Introduction to Design Patterns Tim Burke References: –Gamma, Erich, et. al. (AKA, The Gang of Four). Design Patterns: Elements of Reusable.
Powerpoint Templates Page 1 Powerpoint Templates What is Design Patterns ? by Indriati Teknik Informatika – UB.
SOFTWARE DESIGN AND ARCHITECTURE LECTURE 27. Review UML dynamic view – State Diagrams.
Design Patterns CSCI 5801: Software Engineering. Design Patterns.
18 April 2005CSci 210 Spring Design Patterns 1 CSci 210.
Software Design Patterns (1) Introduction. patterns do … & do not … Patterns do... provide common vocabulary provide “shorthand” for effectively communicating.
Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.
Design Principle & Patterns by A.Surasit Samaisut Copyrights : All Rights Reserved.
ECE450S – Software Engineering II
Patterns in programming1. 2 What are patterns? Answers to common design problems. A language used by developers –To discuss answers to design problems.
Design Patterns CSIS 3701: Advanced Object Oriented Programming.
1 Design Patterns Object-Oriented Design. 2 Design Patterns 4Reuse of design knowledge and experience 4Common in many engineering disciplines 4Avoids.
Behavioral Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
Copyright © Active Frameworks Inc. - All Rights Reserved - V2.0Design Pattern Catalog - Page L3-1 PS95&96-MEF-L10-1 Dr. M.E. Fayad Creationa.
Design Pattern. Definition: A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design.
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)
Design Patterns. 1 Paradigm4 Concepts 9 Principles23 Patterns.
Design Patterns Introduction
Java Design Patterns Java Design Patterns. What are design patterns? the best solution for a recurring problem a technique for making code more flexible.
BEHAVIORAL PATTERNS 13-Sep-2012 Presenters Sanjeeb Kumar Nanda & Shankar Gogada.
CS251 – Software Engineering Lectures 18: Intro to DP Slides by Rick Mercer, Christian Ratliff, Oscar Nierstrasz and others 1 و ابتغ فيما آتاك الله الدار.
Five Minute Design Patterns Doug Marttila Forest and the Trees May 30, 2009 Template Factory Singleton Iterator Adapter Façade Observer Command Strategy.
CLASSIFICATION OF DESIGN PATTERNS Hladchuk Maksym.
Design Patterns CSCE 315 – Programming Studio Spring 2013.
Design Patterns: MORE Examples
The Object-Oriented Thought Process Chapter 15
Chapter 10 Design Patterns.
Chapter 5:Design Patterns
Software Design Patterns
MPCS – Advanced java Programming
Introduction to Design Patterns
Design Patterns Lecture part 2.
Introduction to Design Patterns
Design Patterns Introduction
object oriented Principles of software design
SOEN 343 Software Design Computer Science and Software Engineering Department Concordia University Fall 2005 Instructor: Patrice Chalin.
Software Engineering Lecture 7 - Design Patterns
Design Patterns in Game Design
Informatics 122 Software Design II
Patterns.
DESIGN PATTERNS : Introduction
Informatics 122 Software Design II
Presentation transcript:

Design Patterns (Part 1) Design Patterns are time-tested solutions to recurring design problems. Are the answer to a question that commonly arises “How can I … ?”

Why Study Patterns? Can reuse solutions –Gives us a head start (mostly design, but implementation too) –Avoids unanticipated results as we are using time-tested solutions –No need to reinvent the wheel Establish common terminology –Design patterns provide a common point of reference

Is This A New Idea? Town planners and architects talk of design patterns all the time. Design patterns have their roots in the work of Christopher Alexander an architect. When talking about patterns in buildings and towns in 1977, he wrote “Each pattern describes a problem which occurs over and over again in our environment and then describes the core of the solution to the problem, in such a way that you can use this solution a million times over, without doing it the same way twice.” Christopher Alexander,

Shortly after, software professionals began to incorporate Alexander’s principle into the creation of early design pattern documentation as a guide to novice developers. Design patterns gained popularity in computer science after a certain book was published in 1994 by four authors, commonly know as Gang of Four or GOF

Gang of Four The GoF Book Gang of Four (GoF) Gamma, Helm, Johnson, Vlissides, - founders of movement. Gamma et al, Design Patterns: Elements of Reusable Object-Oriented Software, Addison Wesley, They offer advice and help for developing quality software An object-oriented design pattern systematically names, explains and evaluates an important and recurring design in object-oriented systems

Patterns solve software structural problems like: Abstraction, Encapsulation Information hiding Separation of concerns Coupling and cohesion Separation of interface and implementation Single point of reference Divide and conquer

Patterns also solve non-functional problems like: Changeability Interoperability Efficiency Reliability Testability Reusability

Design Patterns Template TermDescription Pattern NameDescribes the essence of the pattern in a short, but expressive, name IntentDescribes what the pattern does Also Known AsList any synonyms for the pattern MotivationProvides an example of a problem and how the pattern solves that problem ApplicabilityLists the situations where the pattern is applicable StructureSet of diagrams of the classes and objects that depict the pattern ParticipantsDescribes the classes and objects that participate in the design pattern and their responsibilities CollaborationsDescribes how the participants collaborate to carry out their responsibilitiescollaborate ConsequencesDescribes the forces that exist with the pattern and the benefits, trade- offs, and the variable that is isolated by the pattern

Different authors use different templates to describe their patterns Information is not always presented in the same way. Namemeaningful text that reflects the problem, e.g. Bridge, Mediator, Flyweight Problem addressedintent of the pattern, objectives achieved within certain constraints Contextcircumstances under which it can occur Forcesconstraints or issues that solution must address, forces may conflict! Solutionthe static and dynamic relationships among the pattern components. Structure, participants, collaboration. Solution must resolve all forces! Consult your manual/source !!!

Types of Pattern There are 3 types of pattern … –Creational: address problems of creating an object in a flexible way. Separate creation, from operation/use. –Structural: address problems of using O-O constructs like inheritance to organize classes and objects –Behavioral: describe the ways objects and classes interact and divide responsibilities among themselves.

Creational Patterns Abstract Factory –Creates families of related or dependent objects Builder –Separates an object’s construction from its representation Factory Method –Creates instances of several derived classes Prototype –A fully initialized instance to be copied or cloned Singleton –A class of which only a single instance can exist

Structural Patterns Adapter –Match interfaces of different classes Bridge –Separates an object’s interface from its implementation Composite –A tree structure of simple and composite objects Decorator –Add responsibilities to objects dynamically Façade –A single class that represents an entire subsystem Flyweight –A fine-grained instance used for efficient sharing Proxy –An object representing another object

Behavioral Patterns Chain of Responsibility –A way of passing a request between a chain of objects Command –Encapsulate a command request as an object Interpreter –A way to include language elements in a program Iterator –Sequentially access the elements of a collection Mediator –Define simplified communication between classes Memento –Capture and restore an object's internal state Observer –A way of notifying change to a number of classes State –Alter an object's behavior when its state changes Strategy –Encapsulate an algorithm inside a class Template Method –Defer the exact steps of an algorithm to a subclass Visitor –Define a new operation for a class without changing the class

Pattern: Singleton (Creational) Name: Singleton Problem: How can we guarantee that one and only one instance of a class can be created? Context: In some applications it is important to have exactly one instance of a class, e.g. sales of one company, or one shopping basket on website.

Forces: Can make an object globally accessible as a global variable, but this violates encapsulation. Could use class (static) operations and attributes, but polymorphic redefinition is not always possible. Solution: Create a class with a class operation getInstance(). When class is first accessed, this creates relevant object instance and returns object identity to client. On subsequent calls of getInstance(), no new instance is created, but identity of existing object is returned.

Singleton Structure Singleton -uniqueInstance -singletonData +getInstance( ) +getSingletonData( ) +singletonOperation( ) -Singleton( ) Object identifier for singleton instance, class scope or static Returns object identifier for unique instance, class-scope or static Private constructor only accessible via getInstance() getInstance( ) { if ( uniqueInstance == null ) { uniqueInstance = new Singleton( ) } return uniqueInstance }

Class Singleton { private static Singleton uniqueInstance = null; private Singleton( ) {.. } // private constructor public static Singleton getInstance( ) { if (uniqueInstance == null) uniqueInstance = new Singleton(); // call constructor return uniqueInstance; } Example: Code

Real-World Design Pattern Usage The designers of the Microsoft.Net Framework were well aware of many different patterns. Microsoft has a team dedicated to incorporating design patterns into the framework. The Microsoft patterns & practices team works with design patterns and higher-level combinations of patterns

Comments To specify a class has only one instance, we make it inherit from Singleton. + controlled access to single object instance through Singleton encapsulation + Can tailor for any finite number of instances + namespace not extended by global variables -access requires additional message passing -Pattern limits flexibility, significant redesign if singleton class later gets many instances

Singleton Pattern Versus Static Class Static class example [C#] // Static class example. Note the static keyword usage. static public class SiteStatic { // The data must be a static member in this example. static object[] _data = new object[10]; // C# doesn't define when this constructor is run, but it will likely // be run right before it is used. static SiteStatic() { // Initialize all of our static members. } }

Singleton advantages Singletons preserve the conventional class approach, and don't require that you use the static keyword everywhere. They may be more demanding to implement at first, but will greatly simplify the architecture of your program. Unlike static classes, we can use singletons as parameters or objects. Using singleton as parameter [C#] // We want to call a function with this structure as an object. // Get a reference from the Instance property on the singleton. SiteStructure site = SiteStructure.Instance; OtherFunction(site); // Use singleton as parameter.

Interface example You can use singletons with interfaces just like any other class. In the C# language, an interface is a contract, and objects that have an interface must meet all of the requirements of that interface. Singletons used with interface [C#] /// Stores signatures of various important methods related to the site. public interface ISiteInterface { }; /// Skeleton of the singleton that inherits the interface. class SiteStructure : ISiteInterface { // Implements all ISiteInterface methods. // [omitted] } /// Here is an example class where we use a singleton with the interface. class TestClass { public TestClass() { // Send singleton object to any function that can take its interface. SiteStructure site = SiteStructure.Instance; CustomMethod((ISiteInterface)site); } /// Receives a singleton that adheres to the ISiteInterface interface. private void CustomMethod(ISiteInterface interfaceObject) { // Use the singleton by its interface. } }

Singletons allow you to reuse code and control object state much easier. This improves code-sharing, and can result in a far cleaner body of code. With less code, your programs will usually have fewer bugs and will be easier to maintain. Summary

Pattern: Observer (Behavioral) Name: Observer Problem: Define a one-to-many dependency among objects so that when one object changes state, all of its dependents are notified and updated automatically. Solution: MVC, but refined by separating abstract from concrete subjects and observers

Observer ConcreteObserver notify() observerState notify() Subject ConcreteSubject Register(Observer) Unregister(Observer) notifyobservers() subjectState() getState() setState() * * observerState = subject.getState( ) return subjectState for all o in observers { o.notify( ) }

ConcreteSubject notifies its observers whenever a change occurs that could make its observers state inconsistent with its own After being informed of change, a ConcreteObserver queries the subject to reconcile its state with subjects. Observer object that initiates change request postpones its update until it gets notification from subject. Notify() is not always called by subject. Can be called by an observer, or any other object. Pattern is well known, has wide range of variants

Push vs Pull Push means that the observable will always push the data to observers, whether they need it or not. Pull : Observers have the liberty of reaching for the data which makes sense for them [I mean, they might be observing a particular field, but only need to be notified if the field crosses some threshold], and hence can reduce on network traffic, and your application performance.