Software Design Patterns

Slides:



Advertisements
Similar presentations
Chapter 6 Introduction to Design Patterns. Sample Design Goals and Ways to Accomplish Them Reusability, Flexibility, and Efficiency o Reuse flexible designs.
Advertisements

Chapter 6 Introduction to Design Patterns (Part I) COSC 4346: Software Engineering I Dr. Lappoon R. Tang.
Ch:8 Design Concepts S.W Design should have following quality attribute: Functionality Usability Reliability Performance Supportability (extensibility,
Design Patterns Section 7.1 (JIA’s) Section (till page 259) (JIA’s) Section 7.2.2(JIA’s) Section (JIA’s)
Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes.
OOP Design Patterns Chapters Design Patterns The main idea behind design patterns is to extract the high level interactions between objects and.
Chapter 6: Using Design Patterns
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Design Patterns Based on Design Patterns. Elements of Reusable Object-Oriented Software. by E.Gamma, R. Helm, R. Johnson,J. Vlissides.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Design Patterns.
Design Patterns Module Name - Object Oriented Modeling By Archana Munnangi S R Kumar Utkarsh Batwal ( ) ( ) ( )
Chapter 22 Object-Oriented Design
What Is a Factory Pattern?.  Factories are classes that create or construct something.  In the case of object-oriented code languages, factories construct.
BY VEDASHREE GOVINDA GOWDA
Object Oriented Software Development
Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Design Patterns.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
An Introduction to Software Architecture
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.
05 - Patterns Intro.CSC4071 Design Patterns Designing good and reusable OO software is hard. –Mix of specific + general –Impossible to get it right the.
CS 325: Software Engineering March 17, 2015 Applying Patterns (Part A) The Façade Pattern The Adapter Pattern Interfaces & Implementations The Strategy.
An Introduction to Design Patterns. Introduction Promote reuse. Use the experiences of software developers. A shared library/lingo used by developers.
Object-Oriented Software Engineering Practical Software Development using UML and Java Chapter 6: Using Design Patterns 1.
SOFTWARE DESIGN AND ARCHITECTURE LECTURE 27. Review UML dynamic view – State Diagrams.
Software Components Creational Patterns.
Abstract Factory Pattern. What Is an Abstract Factory Pattern?  The Abstract Factory pattern is a creative way to expand on the basic Factory pattern.
The Factory Patterns SE-2811 Dr. Mark L. Hornick 1.
18 April 2005CSci 210 Spring Design Patterns 1 CSci 210.
Object-Oriented Software Engineering Practical Software Development using UML and Java Chapter 6: Using Design Patterns.
Design Principle & Patterns by A.Surasit Samaisut Copyrights : All Rights Reserved.
Chapter 6 Introduction to Design Patterns. Process Phase Discussed in This Chapter Requirements Analysis Design Implementation ArchitectureFrameworkDetailed.
Factory Method Explained. Intent  Define an interface for creating an object, but let subclasses decide which class to instantiate.  Factory Method.
Creational Pattern: Factory Method At times, a framework is needed to standardize the behavior of objects that are used in a range of applications, while.
CSC 480 Software Engineering Design With Patterns.
CS 590L – Distributed Component Architecture 02/20/2003Uttara Paingankar1 Design Patterns: Factory Method The factory method defines an interface for creating.
FACTORY METHOD. Design Pattern Space Purpose ScopeCreationalStructuralBehavioral ClassFactory MethodAdapterInterpreter Template Method ObjectAbstract.
Behavioral Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
Visual Basic for Application - Microsoft Access 2003 Programming applications using Objects.
Object-Oriented Software Engineering Practical Software Development using UML and Java Chapter 6: Using Design Patterns.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
Design Patterns Introduction
1 Chapter 5:Design Patterns. 2 What are design pattern?  Schematic description of design solution to recurring problems in software design and,  Reusable.
Software Design Patterns 1 Gang of Four (GoF, made up of Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides.
Advanced Object-oriented Design Patterns Creational Design Patterns.
CS 325: Software Engineering March 19, 2015 Applying Patterns (Part B) Code Smells The Decorator Pattern The Observer Pattern The Template Method Pattern.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 8 Object Design Reuse and Patterns. More Patterns Abstract Factory: Provide manufacturer independence Builder: Hide a complex creation process.
CS 5150 Software Engineering Lecture 16 Program Design 3.
Reference – Object Oriented Software Development Using Java - Jia COP 3331 Object Oriented Analysis and Design Chapter 10 – Patterns Jean Muhammad.
Banaras Hindu University. A Course on Software Reuse by Design Patterns and Frameworks.
Basic Concepts and Definitions
1 Good Object-Oriented Design Dr. Radu Marinescu Lecture 4 Introduction to Design Patterns.
CLASSIFICATION OF DESIGN PATTERNS Hladchuk Maksym.
Design Patterns: MORE Examples
Design Patterns: Brief Examples
Software Design Patterns
MPCS – Advanced java Programming
Low Budget Productions, LLC
Factory Patterns 1.
Introduction to Design Patterns
Software Design Patterns
Software Engineering Lecture 7 - Design Patterns
Software Design Patterns
CSC 480 Software Engineering
An Introduction to Software Architecture
Lesson 5: More on Creational Patterns
CSC 480 Software Engineering
Presentation transcript:

Software Design Patterns

What is a design pattern? 1. It describes a general usable solution to a recurring problem in an environment 2. It describes core of solution in a procedural-like structure

Why Design Patterns? 1. Simplifies object identification 2. Simplifies system decomposition 3. Proven & tested technique for problem solving 4. Improves speed & quality of design / implementation 5. Can be adapted / refined for specific system under construction

Design Patterns Classification Two categories class scope: relationship between classes & subclasses statically defined at run-time object scope: object relationships (what type?) Can be manipulated at runtime (so what?)

THE CONCEPT OF PATTERNS Construction Architecture Patterns

The term 'pattern' appeals to the replicated similarity in a design The first idea of using patterns was for building and proposed by the architect Christopher Alexander. He found recurring themes in architecture, and captured them into descriptions He called them patterns. The term 'pattern' appeals to the replicated similarity in a design The similarity makes room for variability and customization in each of the elements

Alexander defines: «Each pattern is a three part rule which express a relation between a certain context, a problem and a solution. Each pattern is a relationship between a certain context, a certain system of forces which occurs repeatedly in that context a certain spatial configuration which allows these forces to resolve themselves. A pattern is an instruction and shows how this configuration can be used over and over again. The pattern is a thing that happens in the world The rule which tell us how to create that thing and when we must create it.

KitchenViewer Interface: An architectural pattern example Wall cabinet menu  Counter display area styles Floor cabinet Modern Classic Antique Arts & Crafts

KitchenViewer Example Wall cabinets Floor cabinets Countertop Modern Classic Antique Arts & Crafts

Selecting Antique Style Modern Classic Antique Arts & Crafts

Specific Design Purposes for KitcherViewer The procedure of rendering the various styles is basically the same regardless of the style . The code is as follows: Counter counter =new Counter(); draw (counters); A single block of code that executes in several possible ways, depending on the context  Polymorphism An application must construct a family of objects at runtime. The design must enable choice among several families of styles

An Introduction to Design Pattens Example Application: Without applying a Design Pattern renderKitchen() method is used. This code would have to be repeated for every style The code that is supposed to be duplicated becomes different in different places. Example Application: Applying a Design Pattern renderKitchen(myStyle) method is used KitchenViewer design purpose is implemented by applying Abstract Factory design pattern.

KitchenViewer Without Design Patterns Client renderKitchen() Kitchen WallCabinet FloorCabinet ModernWallCabinet AntiqueWallCabinet ModernFloorCabinet AntiqueFloorCabinet

Without Applying Design Patterns renderKitchen() method have to be repeated for every style The method results in more prone-error and far less maintainable code Sooner and later, code that is supposed to be duplicated becomes different in different places. The result is repetitive and complicated . It is inflexible, hard to prove correct, and hard to reuse

Applying Abstract Factory Design Pattern The object will have responsibility for creating the kitchen . Instead of creating the object directly (for example AntiqueWallCabinet objects), a parameterized version is used for renderKitchen() At run time, the class of myStyle determines the version of getWallCabinet()executed. The KitchenStyle method is introduced and called This class has subclasses , and each support separate implementations of getWallCabinet() and getFloorCabinet()

The Abstract Factory Idea KitchenStyle getWallCabinet() getFloorCabinet() WallCabinet FloorCabinet … AntiqueWallCabinet … AntiqueFloorCabinet ModernKStyle getWallCabinet() getFloorCabinet() AntiqueKStyle getWallCabinet() getFloorCabinet() FloorCabinet getFloorCabinet() { return new ModernFloorCabinet(); } FloorCabinet getFloorCabinet() { return new AntiqueFloorCabinet(); }

Processing the Abstract Factory Pattern: KitchenViewer KitchenViewer design purpose is implemented by applying Abstract Factory design pattern. AntiqueWallCabinet objects are not created directly. A parameterized version of renderKitchen() delegates their creation such as the following: new AntiqueWallCabinet();//applies only to antique style. myStyle.getWallCabinet(); //applies to the style chosen at run time. .

Processing the Abstract Factory Pattern: KitchenViewer At run time , the class of myStyle determines the version of getWallCabinet() and produces the appropriate kind of wall cabinet

Processing the Abstract Factory Pattern: KitchenViewer To carry out this process, a new class KitchenStyle is introduced. KitchenStyle supports the methods getWallCabinet(), getFloorCabinet() and so on. KitchenStyle have subclasses ModernStyle, AntiqueStyle.

Due to the polymorphism, executing myStyle.getFloorCabinet() has differently effects when myStyle is an object of ModernKStyle versus an object of AntiqueKStyle. Client code references Kitchen, KitchenStyle,WallCabinet and FloorCabinet, but does not appear in the client code.

Abstract Factory Design Pattern Applied to KitchenViewer Client renderKitchen( KitchenStyle ) Abstract Factory Design Pattern Applied to KitchenViewer KitchenStyle getWallCabinet() getFloorCabinet() Kitchen getWallCabinet() getFloorcabinet() WallCabinet FloorCabinet ModernWallCabinet ModernKStyle getWallCabinet() getFloorCabinet() AntiqueWallCabinet AntiqueKStyle getWallCabinet() getFloorCabinet() ModernFloorCabinet AntiqueFloorCabinet

Abstract Factory Design Pattern Properties Provide an interface for creating families of related or dependent objects without specifying their concrete classes. A hierarchy that encapsulates: many possible platforms, and the construction of a suite of products. The new operator considered harmful Problem If an application is to be portable, it needs to encapsulate platform dependencies. These platforms might include: windowing system, operating system, database…

Abstract Factory Pattern General Structure: Abstract Factory Pattern The Abstract Factory defines a Factory Method per product. Each Factory Method encapsulates the new operator and the concrete, platform-specific, product classes. Each platform is then modeled with a Factory derived class.

The Factory Method Pattern Product Defines the interface for the type of objects the factory method creates ConcreteProduct Implements the Product interface Creator Declares the factory method, which returns an object of type Product ConcreteCreator Overrides the factory method to return an instance of a ConcreteProduct Creator relies on its subclasses to implement the factory method so that it returns an instance of the appropriate ConcreteProduct

The Factory Method Pattern Code is made more flexible and reusable by the elimination of instantiation of application-specific classes Code deals only with the interface of the Product class and can work with any ConcreteProduct class that supports this interface Clients might have to subclass the Creator class just to instantiate a particular ConcreteProduct Creator can be abstract or concrete Should the factory method be able to create multiple kinds of products? If so, then the factory method has a parameter (possibly used in an if-else!) to decide what object to create

Factory Design Pattern Online bookstores that can choose different book distributors to ship the books to the customers Both BookStoreA and BookStoreB choose which distributor (EastCoastDistributor or MidWestDistributor or WestCoastDistributor) to use based on the location of the customer. This logic is in each bookstore's GetDistributor method.

Abstract Factory Pattern The abstract factory design pattern is an extension of the factory method pattern, The abstract factory pattern allows to create objects without being concerned about the actual class of the objects being produced. The abstract factory pattern extends the factory method pattern by allowing more types of objects to be produced.

Extension of GetDistributor() Method to Abstract Factory Pattern We can extend GetDistributor() method by Adding another product that the factories can produce. In this example, we will add Advertisers that help the bookstores advertise their stores online. Each bookstore can then choose their own distributors and advertisers inside their own GetDistributor and GetAdvertiser method.

public void Advertise(IBookStore s) { IAdverister a = s.GetAdvertiser(); a.Advertise(); }

This allows to have client code (calling code) such as: public void Advertise(IBookStore s) { IAdverister a = s.GetAdvertiser(); a.Advertise(); } Regardless if you pass in BookStoreA or BookStoreB into the method, this client code does not need to be changed since it will get the correct advertiser automatically using the internal logics within the factories. It is the factories (BookStoreA and BookStoreB) that determines which advertiser to produce. The same goes for choosing which book distributor to produce

Abstract Factory Design Pattern

The Benefit of the Abstract Factory Pattern The benefit of the Abstract Factory pattern is that it allows you to create a groups of products (the distributors and the advertisers) without having to know the actual class of the product being produced. The result is that you can have client code that does not need to be changed when the internal logic of the factories changed. We can change the types of the products (the distributors and the advertisers) by changing the code in the factories (the bookstores) without changing the client code

public enum CustomerLocation { EastCoast, WestCoast } class Program { static void Main(string[] args) IBookStore storeA = new BookStoreA(CustomerLocation.EastCoast); Console.WriteLine("Book Store A with a customer from East Coast:"); ShipBook(storeA); Advertise(storeA); IBookStore storeB = new BookStoreB(CustomerLocation.WestCoast); Console.WriteLine("Book Store B with a customer from West Coast:"); ShipBook(storeB); Advertise(storeB); }

//. client code that does not need to be changed //**** client code that does not need to be changed *** private static void ShipBook(IBookStore s) { IDistributor d = s.GetDistributor(); d.ShipBook(); } //**** client code that does not need to be changed *** private static void Advertise(IBookStore s) { IAdvertiser a = s.GetAdvertiser(); a.Advertise();

public interface IBookStore { IDistributor GetDistributor(); //the factory public interface IBookStore { IDistributor GetDistributor(); IAdvertiser GetAdvertiser(); } //concrete factory public class BookStoreA : IBookStore { private CustomerLocation location; public BookStoreA(CustomerLocation location) this.location = location; }

IDistributor IBookStore.GetDistributor() { //internal logic on which distributor to return / /*** logic can be changed without changing the client code **** switch (location) case CustomerLocation.EastCoast: return new EastCoastDistributor(); case CustomerLocation.WestCoast: return new WestCoastDistributor(); } return null;

IAdvertiser IBookStore.GetAdvertiser() { //internal logic on which distributor to return //*** logic can be changed without changing the client code **** switch (location) case CustomerLocation.EastCoast: return new RedAdvertiser(); case CustomerLocation.WestCoast: return new BlueAdvertiser(); } return null; } //end of factory class

{ private CustomerLocation location; public class BookStoreB : IBookStore //concrete factory { private CustomerLocation location; public BookStoreB(CustomerLocation location) { this.location = location; } IDistributor IBookStore.GetDistributor() { switch (location) { case CustomerLocation.EastCoast: return new EastCoastDistributor(); case CustomerLocation.WestCoast: return new WestCoastDistributor(); } return null; } IAdvertiser IBookStore.GetAdvertiser() {switch (location) return new BlueAdvertiser(); return new RedAdvertiser(); } return null; } }

//the product public interface IDistributor { void ShipBook(); } //concrete product public class EastCoastDistributor : Idistributor { void IDistributor.ShipBook() Console.WriteLine("Book shipped by East Coast Distributor"); } } public class WestCoastDistributor : IDistributor Console.WriteLine("Book shipped by West Coast Distributor"); } }

public interface IAdvertiser //the product { void Advertise(); } public class RedAdvertiser : IAdvertiser //concrete product void IAdvertiser.Advertise() { Console.WriteLine("Advertised by RedAdvertiser"); } } public class BlueAdvertiser : IAdvertiser //concrete product void IAdvertiser.Advertise() { Console.WriteLine("Advertised by BlueAdvertiser"); } }

Structural Design Patterns In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities The adapter pattern is a design pattern that is used to allow two incompatible types to communicate. Where one class relies upon a specific interface that is not implemented by another class, the adapter acts as a translator between the two types.

Adapter pattern Adapter pattern is structural pattern which defines a manner for creating relationships between objects. This pattern translates one interface for a class into another compatible interface. Adapter pattern is newer used when creating a new system. It is usually implemented when requirements are changed and we must implement some functionality of classes which interfaces are not compatible with ours.

Adapter Design Pattern Client: represents the class which need to use an incompatible interface. This incompatible interface is implemented by Adaptee. ITarget: defines a domain-specific interface that client uses. In this case it is an simple interface, but in some situations it could be an abstract class which adapter inherits. In this case methods of this abstract class must be overriden by concrete adapter. Adaptee: represents a class provides a functionality that is required by client. Adapter: is concrete implementation of adapter. This class translates incompatible interface of Adaptee into interface of Client.

static class Program { static void Main() { var client = new Client(new Adapter()); client.Request(); } public interface ITarget void MethodA(); } public class Client private readonly ITarget _target; public Client(ITarget target) { _target = target; } public void Request() { _target.MethodA(); }

public class Adaptee { public void MethodB() { Console.WriteLine("Adaptee's MethodB called"); } } public class Adapter : ITarget readonly Adaptee _adaptee = new Adaptee(); public void MethodA() { _adaptee.MethodB(); }

Bridge Pattern Simple inheritance cannot meet the immediate needs where abstraction is not desired. When abstraction or inheritance is used, you are tied to the exact definition of that abstraction. Some cases would require classes not to be inherited instead we would like to adapt other classes to act as the desired type without modifying either class.

The adapter houses an instance variable of the desired type to adapt as a private instance variable. This instance variable is not changeable in the class. This means it is not set as an abstract or base variable but as a concrete type. We hide this instance variable’s methods, properties, and events behind overridden methods, properties

Behavioral Patterns Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes. They use inheritance to control code flow. They define and produce process and run-time flow and identify hierarchies of classes and when and where they become instantiated in code. Some define class instance Some hand off work from one class to another, and Some provide placeholders for other functionality.

Command Pattern An object that contains a symbol, name or key that represents a list of commands, actions or keystrokes. This is the definition of a macro The Macro represents a command that is built from the reunion of a set of other commands, in a given order. Just as a macro, the Command design pattern encapsulates commands (method calls) in objects allowing us to issue requests without knowing the requested operation or the requesting object.

Command Pattern The Command pattern has three main components: The invoker component acts as a link between the commands and the receiver houses the receiver and the individual commands as they are sent. The command is an object that encapsulates a request to the receiver. The receiver is the component that is acted upon by each request.

Command Pattern Command design pattern provides the options to queue commands, undo/redo actions other manipulations. Intent encapsulate a request in an object allows the parameterization of clients with different requests allows saving the requests in a queue

Placing Orders for Buying and Selling Stocks public interface Order { public abstract void execute ( ); } // Receiver class. class StockTrade { public void buy() { System.out.println("You want to buy stocks"); public void sell() { System.out.println("You want to sell stocks ");

// Invoker. class Agent { private m_ordersQueue = new ArrayList(); public Agent() { } void placeOrder(Order order) { ordersQueue.addLast(order); order.execute(ordersQueue.getFirstAndRemove());

//ConcreteCommand Class //ConcreteCommand Class. class BuyStockOrder implements Order { private StockTrade stock; public BuyStockOrder ( StockTrade st) { stock = st; } public void execute( ) { stock . buy( );

//ConcreteCommand Class //ConcreteCommand Class. class SellStockOrder implements Order { private StockTrade stock; public SellStockOrder ( StockTrade st) { stock = st; } public void execute( ) { stock . sell( );

// Client public class Client { public static void main(String[] args) { StockTrade stock = new StockTrade(); BuyStockOrder bsc = new BuyStockOrder (stock); SellStockOrder ssc = new SellStockOrder (stock); Agent agent = new Agent(); agent.placeOrder(bsc); // Buy Shares agent.placeOrder(ssc); // Sell Shares }