OO Design Patterns Overview: Creational, Structural and Behavioral Patterns for OO Design Svetlin Nakov Technical Trainer www.nakov.com Software University.

Slides:



Advertisements
Similar presentations
DESIGN PATTERNS OZGUR RAHMI DONMEZ.
Advertisements

Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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.
Design Patterns Module Name - Object Oriented Modeling By Archana Munnangi S R Kumar Utkarsh Batwal ( ) ( ) ( )
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.
AngularJS Services Built-in and Custom Services SoftUni Team Technical Trainers Software University
Implementing Design Patterns Using Java St. Louis Java Special Interest Group Eric M. Burke Object Computing, Inc. Presented on July 9, 1998 (updated July.
Software University Curriculum, Courses, Exams, Jobs SoftUni Team Technical Trainers Software University
Design Patterns: Introduction. Creational Design Patterns General and reusable solutions to common problems in software design Software University
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.
General and reusable solutions to common problems in software design Learning & Development Telerik Software Academy.
AngularJS Directives Defining Custom Directives SoftUni Team Technical Trainers Software University
Design Patterns: Structural Design Patterns
SOEN 6011 Software Engineering Processes Section SS Fall 2007 Dr Greg Butler
Patterns in programming 1. What are patterns? “A design pattern is a general, reusable solution to a commonly occurring problem in software. A design.
SOFTWARE DESIGN AND ARCHITECTURE LECTURE 27. Review UML dynamic view – State Diagrams.
Loops Repeating Code Multiple Times SoftUni Team Technical Trainers Software University
Svetlin Nakov Technical Trainer Software University
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.
Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.
Design Patterns Introduction General and reusable solutions to common problems in software design SoftUni Team Software University
ECE450S – Software Engineering II
Design Patterns CSIS 3701: Advanced Object Oriented Programming.
What to know for the exam. Smalltalk will be used for questions, but there will not be questions about the grammar. Questions might ask – how particular.
Asynchronous Web Services Writing Asynchronous Web Services SoftUni Team Technical Trainers Software University
DESIGN PATTERNS COMMONLY USED PATTERNS What is a design pattern ? Defining certain rules to tackle a particular kind of problem in software development.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Jekyll Static Site Generator Template-Based Site Generation Svetlin Nakov Technical Trainer Software University
Forms Overview, Query string, Submitting arrays, PHP & HTML, Input types, Redirecting the user Mario Peshev Technical Trainer Software.
CS 210 Final Review November 28, CS 210 Adapter Pattern.
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.
High-Quality Programming Code Code Correctness, Readability, Maintainability Svetlin Nakov Technical Trainer Software University
Example to motivate discussion We have two lists (of menu items) one implemented using ArrayList and another using Arrays. How does one work with these.
Design Patterns: Structural Design Patterns General and reusable solutions to common problems in software design Software University
Design Patterns II Structural, Behavioral and Others SoftUni Team Software University
Object-Oriented Programming Course Introduction Svetlin Nakov Technical Trainer Software University
StarBuzz Coffee Recipe Boil some water Brew coffee in boiling water Pour coffee in cup Add sugar and milk Tea Recipe Boil some water Steep tea in boiling.
Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Design Patterns: Behavioral Design Patterns General and reusable solutions to common problems in software design Software University
Mocking Unit Testing Methods with External Dependencies SoftUni Team Technical Trainers Software University
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
Design Patterns CSCE 315 – Programming Studio Spring 2013.
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Generics SoftUni Team Technical Trainers Software University
Design Patterns: MORE Examples
Describe ways to assemble objects to implement a new functionality
Chapter 10 Design Patterns.
Chapter 5:Design Patterns
Software Design Patterns
MPCS – Advanced java Programming
Introduction to Design Patterns
Design Patterns Lecture part 2.
Best Practices and Architecture
Introduction to Design Patterns
Iterators and Comparators
object oriented Principles of software design
Advanced Programming Behnam Hatami Fall 2017.
Object Oriented Design Patterns - Structural Patterns
Presentation transcript:

OO Design Patterns Overview: Creational, Structural and Behavioral Patterns for OO Design Svetlin Nakov Technical Trainer Software University

2 1.What are Design Patterns?1.What are Design Patterns? 2.Types of Design Patterns2.Types of Design Patterns 3.Creational Patterns3.Creational Patterns 4.Structural Patterns4.Structural Patterns 5.Behavioral Patterns5.Behavioral Patterns 6.Other Patterns6.Other Patterns Table of Contents

What are Design Patterns?What are Design Patterns? Name, Problem, Solution and Consequences

4  Software design pattern  Reusable solutions to common problems in software design  Problem / solution pairs within a given context  A template or recipe for solving certain software design problems  GoF patterns  Classical object-oriented design patterns book by Gama, Helm, Johnson, Vlissides 1995  The "Gang of Four Book"  Creational, structural and behavioural patterns What is a Design Pattern?

5  Design patterns are described by a few essential elements:  Pattern Name  Increases vocabulary of designers  Problem  Intent, context, when to apply  Solution  UML-like structure, abstract code  Consequences  Results and tradeoffs Elements of Design Patterns

Types of Design Patterns

7  Creational patterns  Deal with initializing and configuring classes and objects  Structural patterns  Describe ways to assemble objects to implement a new functionality  Composition of classes or objects  Behavioral patterns  Deal with dynamic interactions among societies of classes and objects  How they distribute responsibilities Three Main Types of OO Design Patterns

Creational Patterns

9  Deal with object creation mechanisms  Trying to create objects in a manner suitable to the situation  Instead of " new SomeClass() " use " pattern.Create() "  Composed of two dominant ideas  Encapsulating knowledge about which concrete classes the system uses  Hiding how instances of these concrete classes are created and combined Creational Patterns

10  The Singleton class is a class that is supposed to have only one (single) instanceSingleton  Usually created on demand (lazy loading)  Sometimes Singleton is wrongly thought of as a global variable  It is not!  Possible problems:  Thread-safe Singleton Pattern

11 Singleton – Example public sealed class Singleton { private Singleton() { } private Singleton() { } private static readonly Singleton instance = new Singleton(); private static readonly Singleton instance = new Singleton(); public static Singleton Instance public static Singleton Instance { get get { return instance; return instance; } }}

12  In object-oriented programming, a Factory is an object for creating other objects (alternative constructor)Factory  Not a GoF pattern; often mistaken with the Factory Method  Traditional object creation: new + constructor call  Creating objects through factory (usually a static method): Factory DateTime t = new DateTime(2014, 10, 16); DateTime t = DateTime.Now; Color c = Color.FromArgb(120, 255, 0, 0);

13 Factory – Example public class Complex { private double real; private double real; private double imaginary; private double imaginary; public static Complex FromPolarFactory(double modulus, double angle) public static Complex FromPolarFactory(double modulus, double angle) { return new Complex( return new Complex( modulus * Math.Cos(angle), modulus * Math.Sin(angle)); modulus * Math.Cos(angle), modulus * Math.Sin(angle)); } private Complex(double real, double imaginary) private Complex(double real, double imaginary) { this.real = real; this.real = real; this.imaginary = imaginary; this.imaginary = imaginary; }} Complex complexNum = Complex.FromPolarFactory(1, Math.PI / 3);

14  Factories may have many variants  Static / non-static method for creating products  Return the product class / product subclass  Factory inside / outside the product class  Example:  Coffee class – holds a mix of coffee and milk  CoffeeFactory class – creates coffee, cappuccino / macchiato  Depending on the coffee type requested Factory: Variants

15  Factory Method Factory Method  Creates objects without specifying their exact class  Crates subclasses, but returns the base abstract class / interface  Benefits  Allows adding new subclasses later  Easier extensibility  Better maintainability Factory Method Pattern

16 Factory Method – Example public abstract class Product { … } public class Chair : Product { … } public class Table : Product { … } public abstract class ProductCreator { public abstract Product CreateProduct(); public abstract Product CreateProduct();} public class TableCreator : ProductCreator { public override Product CreateProduct() { return new Table(…); } public override Product CreateProduct() { return new Table(…); }} public class ChairCreator : ProductCreator { public override Product CreateProduct() { return new Chair(…); } public override Product CreateProduct() { return new Chair(…); }}

Structural Patterns

18  Structural patterns describe ways to assemble objects to implement a new functionality  Define how different classes and objects are combined to form larger structures  Structural class patterns use inheritance to compose interfaces or implementations  Structural object patterns compose objects for new functionality  Examples of structural design patterns:  Composite, Decorator, Façade, Adapter, Bridge, Proxy Structural Patterns

19  Façade provides a simplified interface to a larger body of code  Higher level interface hides the complexity of subsystems  Similar pattern: Adapter – converts between interfaces Façade Pattern

20 Façade – Example interface IAESFacade { string AESEncrypt(string message, string password); string AESEncrypt(string message, string password); byte[] AESEncrypt(byte[] bytesToBeEncrypted, string password); byte[] AESEncrypt(byte[] bytesToBeEncrypted, string password); byte[] AESDecrypt(byte[] bytesToBeDecrypted, string password); byte[] AESDecrypt(byte[] bytesToBeDecrypted, string password); string AESDecrypt(string encryptedMessage, string password); string AESDecrypt(string encryptedMessage, string password);} class AESFacade : IAESFacade { public string AESEncrypt(string message, string password) { … } public string AESEncrypt(string message, string password) { … } public byte[] AESEncrypt(byte[] bytes, string password) { … } public byte[] AESEncrypt(byte[] bytes, string password) { … } public byte[] AESDecrypt(byte[] bytes, string password) { … } public byte[] AESDecrypt(byte[] bytes, string password) { … } public string AESDecrypt(string msg, string password) { … } public string AESDecrypt(string msg, string password) { … }}

21  Composite Pattern allows to combining different types of objects in tree structures  Treats the same individual objects or groups of objects  Example:  Build a document system  Used when  You have different objects and you want to treat them the same way  You want to present a hierarchy of objects Composite Pattern

22 Composite – Example public interface IComponent { … } public interface ICompositeComponent : IComponent { void Add(Component page); void Add(Component page); void Remove(Component page); void Remove(Component page);} public class Commander : ICompositeComponent { private ICollection childComponents = private ICollection childComponents = new List (); new List (); public override void Add(Component component) public override void Add(Component component) { this.childComponents.Add(component); } { this.childComponents.Add(component); } public override void Remove(Component component) public override void Remove(Component component) { this.childComponents.Remove(component); } { this.childComponents.Remove(component); }}

23  Controls in Windows Forms  Class System.Windows.Forms.Control holds child controls  Properties Controls, HasChildren, …  Controls in ASP.NET Web Forms  Class System.Web.UI.Control holds child controls  Property Controls  Controls in AWT / Java Swing  Classes java.awt.Component, java.awt.Container Composite – Real World ExamplesComposite – Real World Examples

24  Decorator adds responsibilities to objects dynamically  Wrapping original component  Alternative to inheritance (class explosion)  Supports the Open-Closed principle Decorator Pattern

25 Decorator – Example public abstract class Pizza { public abstract string GetDescription(); public abstract string GetDescription(); public abstract decimal GetPrice(); public abstract decimal GetPrice();} public class TomatoSaucePizza : Pizza { private Pizza basePizza; private Pizza basePizza; public TomatoSaucePizza(Pizza pizza) public TomatoSaucePizza(Pizza pizza) { this.basePizza = pizza; } { this.basePizza = pizza; } public override string GetDescription() public override string GetDescription() { return this.basePizza.GetDescription() + " + Tomato Sauce"; } { return this.basePizza.GetDescription() + " + Tomato Sauce"; } public override decimal GetPrice() public override decimal GetPrice() { return basePizza.GetPrice() m; } { return basePizza.GetPrice() m; }}

26 in.NET decorates  BufferedStream in.NET decorates Stream  CryptoStream decorates Stream in Java  BufferedReader in Java Decorator – Real World ExamplesDecorator – Real World Examples BufferedReader bufferedReader = new BufferedReader( new BufferedReader( new InputStreamReader( new InputStreamReader( new FileInputStream( new FileInputStream( new File("file_name.txt")))); new File("file_name.txt")))); CryptoStream crStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write); encryptor, CryptoStreamMode.Write);

27  Adapter converts the given class' interface into another class requested by the client  Wrap an existing class with a new interface  Impedance match an old component to a new system  Allows classes to work together when this is impossible due to incompatible interfaces Adapter Pattern

28 Adapter – Example class ChemicalDatabank { public float GetMolecularStructure(string compound) {…} public float GetMolecularStructure(string compound) {…} …} interface ICompound { void Display(); void Display();} public RichCompound : ICompound { public RichCompound(string compound) { public RichCompound(string compound) { var chemicalBank = new ChemicalDatabank(); var chemicalBank = new ChemicalDatabank(); } public void Display() {…} public void Display() {…}} Legacy class Needed interface Adapter class

Behavioral Patterns

 Behavioral patterns are concerned with communication (interaction) between the objects  Either with the assignment of responsibilities between objects  Or encapsulating behavior in an object and delegating requests to it  Increase flexibility in carrying out cross-classes communication  Classical behavioral patterns:  Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Null Object, Observer, State, Strategy, Template Method, Visitor 30

31  Iterator allows access to the elements of a complex object without revealing its actual presentation  Various ways of data structure traversing  Unified interface for iterating over various data structures  Iterator allows access to the elements of a complex object without revealing its actual presentation  Various ways of data structure traversing  Unified interface for iterating over various data structures Iterator Pattern

32 Iterator – Example public interface IEnumerator { bool MoveNext(); object Current { get; } void Reset(); } public interface IEnumerable { IEnumerator GetEnumerator(); IEnumerator GetEnumerator();} private class ConcreteEnumerator : IEnumerator { // Implement IEnumerator interface // Implement IEnumerator interface} var enumerator = someObject.GetEnumerator(); enumerator.Reset(); while (enumerator.MoveNext()) { // Process the enumerator.Current // Process the enumerator.Current}

33  IEnumerable / foreach in C#  Iterable in Java Iterator – Real World Examples IEnumerator GetEnumerator() { foreach(var element in this.array) { yield return element; yield return element; }} public boolean hasNext() { if (count < str.length()) { return true; } else return false; else return false; } public Character next() { return str.charAt(count++); }

34  Template Method defines the base of an algorithm in a method, leaving some implementation to its subclasses  Allows the subclasses to redefine the implementation of some of the parts of the algorithm  Doesn’t let the subclasses to change the algorithm structure Template Method Pattern

35 Template Method – Example public abstract class HotDrink { public void PrepareRecipe() { BoilWater(); Brew(); PourInCup(); AddSpices(); } protected abstract void Brew(); protected abstract void AddSpices(); private void BoilWater() {... } private void PourInCup() {... } } public class Coffee : HotDrink { protected override void Brew() {... } protected override void AddSpices() {... } } public class Tea : HotDrink { protected override void Brew() {... } protected override void AddSpices() {... } } Implemented by subclasses

36 in Java  Thread.run() in Java in.NET  Thread.Start() in.NET Template Method – Real World ExamplesTemplate Method – Real World Examples Thread thread = new Thread(){ public void run() { public void run() { System.out.println("Thread is running."); System.out.println("Thread is running."); }};thread.start(); Thread thread = new Thread( () => Console.WriteLine("Thread is running.")); () => Console.WriteLine("Thread is running."));thread.Start();

37  Observer presents interface, allowing object to communicate without any concrete knowledge about each other  Also known as Publish-Subscribe pattern  Object to inform other object about its state, without the knowledge which are these objects Observer Pattern

38  Events and event handlers in.NET  Events sources (components) publish events (e.g. Button )  Events in.NET provide subscribing mechanisms (e.g. Click )  java.util.Observable / java.util.Observer  Classical observer pattern  ActionListener in Java  java.awt.event.ActionListener has actionPerformed()  java.awt.Button has addActionListener() – Real World ExamplesObserver – Real World Examples

39  Strategy encapsulates an algorithm inside a class  Making each algorithm replaceable by others  All the algorithms can work with the same data transparently  The client can transparently work with each algorithm Strategy Pattern

40 abstract class SortStrategy { public abstract void Sort(IList list); } class QuickSort : SortStrategy { public override void Sort(IList list) { … } public override void Sort(IList list) { … }} class SortedList { private IList list = new List (); private IList list = new List (); public void Sort(SortStrategy strategy) { public void Sort(SortStrategy strategy) { // sortStrategy can be passed in constructor // sortStrategy can be passed in constructor sortStrategy.Sort(list); sortStrategy.Sort(list); }} class MergeSort : SortStrategy { public override void Sort(IList list) { … } public override void Sort(IList list) { … }}

41  IComparer, Cloneable in.NET  Sorting uses IComparer as strategy for comparing items  The Cloneable is a strategy for cloning objects  Comparer in Java  Sorting uses Comparer as strategy for comparing items  TreeMap uses Comparer as strategy for ordering the tree nodes Strategy – Real World ExamplesStrategy – Real World Examples

Architectural Patterns

43  Client-Server Model – client ↔ server Client-Server Model  3-tier Architecture – front-end ↔ logic tier ↔ back-end 3-tier Architecture  Multi-tier Architecture Multi-tier Architecture  Model-View-Controller (MVC) – for creating UI Model-View-Controller  Model-View-Presenter (MVP) – for creating UI Model-View-Presenter  Model-View-ViewModel (MVVM) – for creating UI Model-View-ViewModel  Front Controller – for dispatching requests in Web applications Front Controller  Active Record – wrap database tables in classes + CRUD operations Active Record Architectural Patterns

44  Design patterns  Reusable solutions for common OO design problems  Creational patterns  Singleton, Factory, Factory Method  Structural patterns  Façade, Composite, Decorator, Adapter  Behavioral patterns  Iterator, Observer, Template Method, Strategy Summary

? ? ? ? ? ? ? ? ? OO Design Patterns

License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International 46  Attribution: this work may contain portions from  "OOP" course by Telerik Academy under CC-BY-NC-SA licenseOOPCC-BY-NC-SA

SoftUni Diamond Partners

Free Software University  Software University Foundation – softuni.orgsoftuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg softuni.bg  Software Facebook  facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity  Software YouTube  youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bgforum.softuni.bg