Lecture 3 - Design Patterns PDF
Document Details
Uploaded by GracefulAllegory
Destaye A
Tags
Summary
This lecture provides an overview of design patterns in software development. Covering the origins, examples, and various types of design patterns.
Full Transcript
Chapter 3 Design Patterns By Destaye A. Contents Introduction: Origine of Design Patterns What are design patterns? Examples of patterns Benefits Patterns Types of design patterns Creational Design Patterns Factory Method Singlet...
Chapter 3 Design Patterns By Destaye A. Contents Introduction: Origine of Design Patterns What are design patterns? Examples of patterns Benefits Patterns Types of design patterns Creational Design Patterns Factory Method Singleton Pattern Structural Design Patterns Adapter Pattern Facade Pattern Behavioral Design Pattern Iterator Pattern Origins of Design Patterns “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 What are Design Patterns? Software design pattern is a generalized reusable solution to a commonly occurring problem in software design in defined context ( the general situation in which pattern applies) A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations Many of them have been systematically documented for all software developers to use A good pattern should be as general as possible contain a solution that has been proven to effectively solve the problem in the indicated context. Elements of Design Patterns Design patterns must be described in an easy-to-understand form so that people can determine when and how to use it. Minimum parameters to describe patterns are Name - Important because it becomes part of a design vocabulary Problem - describes intent, context, and when the pattern is applicable Solution - Design elements and their relationships. Consequences - Tradeoffs of applying the pattern Each pattern has costs as well as benefits Issues include flexibility, extensibility, etc. Each pattern in Gang of Four (GoF) is documented with following specifications: Intent, also known as, motivation, applicability, structure, participants, collaborations, consequences, implementation, sample code, known uses, related patterns Examples of patterns Design patterns you have already seen Encapsulation (Data Hiding) Sub-classing (Inheritance) Iteration Exceptions Encapsulation Pattern Problem: Exposed fields are directly manipulated from outside, leading to undesirable dependences that prevent changing the implementation. Solution: Hide some components, permitting only stylized access to the object. Exemples of patterns… Sub-classing pattern Problem: Similar abstractions have similar members (fields and methods). Repeating these is tedious, error-prone, and a maintenance headache. Solution: Inherit default members from a super-class; select the correct implementation. Iteration pattern Problem: Clients that wish to access all members of a collection must perform a specialized traversal for each data structure. Solution: Implementations perform traversals. The results are communicated to clients via a standard interface. Exceptions Pattern Problem: Code is cluttered with error-handling code. Solution: Errors occurring in one part of the code should often be handled elsewhere. Use language structures for throwing and catching exceptions. Why Patterns? Speed up the development process by providing tested, proven development paradigms. Shared language of design Increases communication bandwidth because it has consistent documentation Decreases misunderstandings Learn from experience Becoming a good designer is hard Understanding good designs is a first step Tested solutions to common problems Used to achieve the following quality attributes; Modifiability, Exchangeability, Reusability, Extensibility, Maintainability, Reliability, Testability, … Patterns help you to manage software complexity. Types of Design Patterns Design pattern are applied at different levels such as frameworks, and subsystems GRASP Patterns General Responsibility Assignment Software Pattern E.g. Information Expert, Creator, Low Coupling, High Cohesion Architectural patterns An architectural pattern express a fondamental structural organisation schéma for software Systems Design patterns Creational Patterns- initializing and configuring classes and objects Structural Patterns - integration and composition of classes and objects Behavioral Patterns -dynamic interactions among societies of classes and objects Idioms An Idiom is a low-level patterns specific to a programming language. Design Patterns space Purpose Defer object creation to another class Creational Structural Behavioral Scope Abstract Factory Adapter (object) Chain of Builder Bridge Responsibility Prototype Composite Command Singleton Decorator Iterator Facade Mediator Flyweight Memento Proxy Observer State Strategy Defer object creation to Visitor another object Describe ways to Describe algorithms and assemble objects flow control AP 04/02 Creational Patterns Abstract the instantiation process Make a system independent of how its objects are created, composed, and represented Creational pattern support the creation process by helping to provide the following capabilities Generic instantiation – allows objects to be created in a system without having to identify a specific class type in code. Simplicity – some patterns make object creation easier so callers will not have to write large, complex code to instantiate an object. Creation constraint – some patterns create constraints on the type or number of objects that can be created within a system. Factory Method pattern The creation of an object often requires complex processes which is not appropriate to include within a composing object. Intent: Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. Factory Method pattern… The participants classes in this pattern are: Product - defines the interface for objects the factory method creates. ConcreteProduct - implements the Product interface. Creator(also refered as Factory because it creates the Product objects) declares the method FactoryMethod, which returns a Product object. May call the generating method for creating Product objects ConcreteCreator - overrides the generating method for creating ConcreteProduct objects Example If we have a super class and n sub-classes, and based on data provided, we have to return the object of one of the sub-classes, we use a factory pattern. Factory Method pattern... Use the Factory Method pattern when a class can´t anticipate the class of objects it must create. a class wants its subclasses to specify the objects it creates. classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate. Consequences: Provides hooks for subclasses Connects parallel class hierarchies Limitations The factory has to be used for a family of objects. If the classes doesn't extend common base class or interface they can not be used in a factory design template. Advantages of Factory Method Design Pattern Separates object creation from client code, enhancing flexibility and maintainability since changes to creation don’t affect clients. New product types can be easily added without altering client code by simply creating new Concrete Creator subclasses. Simplifies unit testing by allowing mock product creation, enabling tests of various implementations without actual object dependencies. The factory method can be reused across different application parts Singleton pattern a class that can have only one object (an instance of the class) at a time. Intent: Ensure a class only has one instance, and provide a global point of access to it. Singleton pattern Example According to the definition the singleton pattern should be used when there must be exactly one instance of a class, and when it must be accessible to clients from a global access point. Here are some real situations where the singleton is used: Examples of use of singleton pattern The Singleton pattern is used in the design of logger classes. This classes are usually implemented as a singletons, and provides a global logging access point in all the application components without being necessary to create an object each time a logging operations is performed. Singleton Pattern is also used when there is a single resource, where there should only be a single object in charge of accessing the single resource. Singleton pattern... Use the Singleton pattern when there must be exactly one instance of a class, and it must be accessible to clients from a well-known access point. when the sole instance should be extensible by sub classing, and clients should be able to use an extended instance without modifying their code. Consequences Controlled access to sole instance Reduced name space Permits refinement of operations and representations Permits a variable number of instances More flexible than class operations purpose of Singleton class to restrict the limit of the number of object creations to only one. This often ensures that there is access control to resources, Memory space wastage does not occur with the use of the singleton class because it restricts instance creation Structural Patterns Structural Design Patterns solves problems related to how classes and objects are composed/assembled to form larger structures which are efficient and flexible in nature. It use inheritance to compose interfaces or implementations. structural object patterns describe ways to compose objects to realize new functionality. The added flexibility of object composition comes from the ability to change the composition at run-time. Structural Patterns Adapter/wrapper Pattern Intent The Adapter design pattern is a structural pattern that allows the interface of an existing class to be used as another interface. It acts as a bridge between two incompatible interfaces, making them work together. This pattern involves a single class, known as the adapter, which is responsible for joining functionalities of independent or incompatible interfaces The classes/objects participating in adapter pattern: Target - defines the domain-specific interface that Client uses. Adapter - adapts the interface Adaptee to the Target interface. Adaptee - defines an existing interface that needs adapting. Client - collaborates with objects conforming to the Target interface The adapter pattern convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces Adapter Pattern … Adapter classes could be object adapter or class adapter Objects Adapters - Based on Delegation Objects Adapter uses composition, the Adaptee delegates the calls to Adaptee (opposed to class adapters which extends the Adaptee). Class Adapter – Based on (Multiple) Inheritance Class adapters can be implemented in languages supporting multiple inheritance. Adapter Pattern … Use Adapter when you want to use an existing class, and its interface doesn’t match the one you need. want to create a reusable class that cooperates with unrelated or unforeseen classes need to use several existing subclasses, but it's impractical to adapt their interface by sub-classing every one. Consequences: A class adapter lets Adapter override some of Adaptee's behavior, since Adapter is a subclass of Adaptee. introduces only one object, and no additional pointer indirection is needed to get to the adaptee. An object adapter lets a single Adapter work with many Adaptees makes it harder to override Adaptee behavior. Facade Pattern Intent: Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use. Make a complex system simpler by providing a unified or general interface, which is a higher layer to these subsystems. Façade Pattern… Use Façade when you want to provide a simple interface to a complex subsystem. there are many dependencies between clients and the implementation classes of an abstraction. you want to layer your subsystems. Consequences: It shields clients from subsystem components It promotes weak coupling between the subsystem and its clients. Behavioral Design Patterns Behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication. Behavioral patterns are those which are concerned with interactions between the objects. The interactions between the objects should be such that they are talking to each other and still are loosely coupled. List of Behavioral Patterns Interpreter Pattern Interpreter pattern is used to defines a grammatical representation for a language and provides an interpreter to deal with this grammar Template Pattern The template method design pattern defines an algorithm as a collection of skeleton operations, with the child classes handling the implementation of the specifics. The parent class maintains the overall structure and flow of the algorithm State Pattern When an object modifies its behavior according to its internal state, the state design pattern is applied. If we have to change the behavior of an object based on its state, we can have a state variable in the Object and use the if-else condition block to perform different actions based on the state.