SlideShare a Scribd company logo
1 of 64
Download to read offline
.NET – DESIGN PATTERN
VERSION (1.0)
MOUDLE NAME
.Net DESIGN PATTERN
SUBMITTED FOR
Saudi Post
SUBMITTED BY
ARCOM
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 2
1. TABLE OF CONTENT
1. TABLE OF CONTENT ...................................................................................................................2
2. REVIEW HISTORY .......................................................................................................................4
2.1. STATUS ..........................................................................................................................................4
2.2. CHANGE HISTORY..........................................................................................................................4
2.3. DISTRIBUTION ...............................................................................................................................5
3. DOCUMENT PURPOSE................................................................................................................6
4. OBJECT-ORIENTED DESIGN PATTERNS .......................................................................................7
5. BASIC ELEMENTS OF A DESIGN PATTERN ...................................................................................8
6. DESIGN PATTERN STYLE GUIDE ..................................................................................................9
7. DESIGN PATTERN TYPES...........................................................................................................10
7.1. CREATIONAL PATTERNS...........................................................................................................11
7.1.1. ABSTRACT FACTORY PATTERN...............................................................................................12
7.1.2. FACTORY METHOD PATTERN.................................................................................................14
7.1.3. BUILDER PATTERN .................................................................................................................16
7.1.4. PROTOTYPE PATTERN............................................................................................................18
7.1.5. SINGLETON PATTERN.............................................................................................................20
7.2. STRUCTURE PATTERNS.............................................................................................................22
7.2.1. FACADE PATTERN ..................................................................................................................23
7.2.2. ADAPTER PATTERN................................................................................................................25
7.2.3. COMPOSITE PATTERN............................................................................................................27
7.2.4. BRIDGE PATTERN...................................................................................................................29
7.2.5. DECORATOR PATTERN...........................................................................................................31
7.2.6. FLYWEIGHT PATTERN ............................................................................................................33
7.2.7. PROXY PATTERN ....................................................................................................................36
4.3. BEHAVIOUR PATTERNS ............................................................................................................39
4.3.1. COMMAND PATTERN ............................................................................................................40
4.3.2. CHAIN OF RESPONSIBILITES PATTERN...................................................................................42
4.3.3. INTERPRETER PATTERN .........................................................................................................44
4.3.4. ITERATOR PATTERN ...............................................................................................................46
4.3.5. MEDIATOR PATTERN .............................................................................................................48
4.3.6. MOMENTO PATTERN.............................................................................................................50
4.3.7. NULL OBJECT PATTERN..........................................................................................................52
4.3.8. OBSERVER PATTERN ..............................................................................................................54
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 3
4.3.9. STATE PATTERN .....................................................................................................................56
4.3.10. STRATEGY PATTERN...............................................................................................................58
4.3.11. TEMPLATE METHOD PATTERN ..............................................................................................60
4.3.12. VISITOR PATTERN ..................................................................................................................62
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 4
2. REVIEW HISTORY
2.1.STATUS
Version 1.0
Status Proposed
2.2.CHANGE HISTORY
Date Author Version Change Reference
10/03/2016 Mohamed Zakarya 1.0 First draft
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 5
2.3.DISTRIBUTION
APPROVERS
Stakeholder Name
CONSULTED
Stakeholder Name
INFORMED
Stakeholder Name
Choose an item.
Choose an item.
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 6
3. DOCUMENT PURPOSE
As we build more complex computer systems, we face problems of construction rather
than problems of analysis. The problems of construction are solved by designing
programming solutions for such problems in the context of the computer application
we are trying to build.
Some constructional problems occur over and over again across a wide range of
different computer applications. Obviously, we can design a generic solution to such
repeating problems, and then try to adjust such a generic solution to the specific need
of the application we are currently building. Such generic solutions are usually referred
to as design patterns.
Christopher Alexander first introduced patterns to encode knowledge and experience
in designing buildings. He said: “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 many times over, without ever
doing it the same way twice”.
Thus, a design pattern is the core of a solution to a problem in context. The solution
can be applied in different situations, and has to be adapted to fit the needs of the
specific situation.
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 7
4. Object-Oriented Design Patterns
Design patterns in programming were first introduced by the Gang of Four (Gamma,
Helm, Johnson, Vlissides). They referred to design patterns always as to object-oriented
design patterns, i.e., design patterns that occur in building object-oriented computer
systems.
Thus, object-oriented design patterns might be defined as descriptions of
communicating objects and classes that are customized to solve a general (object-
oriented) design problem in a particular context.
They also stated that an object-oriented design pattern is not:
 A primitive building block, such as linked lists, or hash-tables that can be
encoded in classes and reused in a wide range of applications
 A complex, domain specific design for an entire application or subsystem.
Rather, an object-oriented design pattern just describes a recurring object-
oriented design structure.
Thus, an object-oriented design pattern:
 Names, abstracts, and identifies the key aspect (classes, objects and their
relations) of a common design structure
 Creates a reusable object-oriented design
 Focuses on a particular object-oriented design by describing when it applies,
whether it can be applying in view of other design constraints, and the
consequences and trade-offs of its use
 Implements the design idea in an object-oriented programming language.
In the rest of this paper we will examine solely object-oriented design patterns. Thus,
whenever we say a design pattern we actually refer to an object-oriented design patter
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 8
5. Basic Elements of a Design Pattern
Each pattern has four essential elements:
 The pattern name is a handle we can use to describe a design problem, its
solutions and consequences in a word or two. Naming a pattern immediately
increases the design vocabulary of programmers. Having a vocabulary for
patterns enables to talk about patterns with other programmers, in the
documentation, etc.
 The problem describes when to apply the pattern. It explains the problem and
its context. It might describe specific design problems such as how to represent
algorithms as objects. It might describe class or object structures that are
symptomatic of an inflexible design. Sometimes the problem includes also a list
of conditions that must be met before it makes sense to apply the pattern.
 The solution describes the elements that make up the design, their
relationships, responsibilities, and collaborations. The solution doesn’t describe
a particular concrete design or implementation, because a pattern is like a
template that can be applied in many different situations. Instead, the pattern
provides an abstract description of a design problem and how a general
arrangement of elements (classes and objects) solves it.
 The consequences are the results and trade-offs of applying the pattern. They
may address language and implementation issues as well. Since reuse is often
a factor in object-oriented design, the consequences of a pattern include its
impact on a system’s flexibility, extensibility, or portability.
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 9
6. DESIGN PATTERN STYLE GUIDE
The description of any pattern will follow the next style guide:
1. OVERVIEW
 Overview about the pattern
2. WHEN TO USE
 What problem you face and when to user this pattern
3. STRUCTURE
 Pattern structure
4. CHECK LIST
 Check list when implement the pattern
5. CONCEPTUAL EXAMPLE
 Real example of using pattern
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 10
7. DESIGN PATTERN TYPES
There is basic pattern that are foundation of other patterns
they are categorized in three groups
1. Creational patterns
2. Structural patterns
3. Behavioural patterns
CREATIONAL PATTERNS
 create objects for you, rather than having you instantiate objects directly.
 This gives your program more flexibility in deciding which objects need to be created
for a given case.
STRUCTURE PATTERNS
 These concern class and object composition.
 Identifying a simple way to realize relationships between entities.
 They use inheritance to compose interfaces and define ways to compose objects to
obtain new functionality.
BEHAVIOUR PATTERNS
 Identify common communication patterns between objects and realize these patterns.
 These patterns increase flexibility in carrying out this communication.
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 11
7.1. CREATIONAL PATTERNS
Creational design patterns are design patterns that deal with object creation
mechanisms, trying to create objects in a manner suitable to the situation
There are basic 6 pattern for creational pattern as follows
PATTERN DESCRIPTION Freq.
of use
Abstract factory Creates an instance of several families of classes 5/5
Factory Method Creates an instance of several derived classes 5/5
Builder Separates object construction from its representation 2/5
Prototype A fully initialized instance to be copied or cloned 3/5
Singleton A class of which only a single instance can exist 4/5
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 12
7.1.1.ABSTRACT FACTORY PATTERN
1. OVERVIEW
 Abstract Factory pattern is a super factory which creates other factories, this
factory is called factory of factories
 This pattern provides one of the best ways to create an object
 Abstract Factory pattern an interface is responsible for encapsulate a group of
individual factories that have a common theme without specifying their
concrete classes
2. WHEN TO USE
 The purpose of the Abstract Factory is to provide an interface for creating
families of related objects, without specifying concrete classes
 providing data access to two different data sources
 supporting multiple platforms while keeping your code-base unified
3. STRUCTURE
Client
 Uses interfaces declared by AbstractFactory and AbstractProduct classes
 Eg. Animal World
AbstractFactory (abstract class)
 declares an interface for operations that create abstract products
 Eg. Continent Factory
ConcreteFactory (normal class)
 implements the operations to create concrete product objects
 extend the abstract factory functionality
 Eg. (AfricaFactory, AmericaFactory)
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 13
AbstractProduct (interface – abstract class)
 declares an interface for a type of product object
 Eg. (Herbivore, Carnivore)
Product (class)
 defines a product to be created by the corresponding concrete factory
 implements the AbstractProduct interface
 Eg. Wildebeest, Lion, Bison, Wolf
4. CHECK LIST
 Map out a matrix of "platforms" versus "products"
 Define a factory interface that consists of a factory method per product.
 Define a factory derived class for each platform that encapsulates all
references to the new operator
 The client should retire all references to new, and use the factory methods to
create the product objects
5. CONCEPTUAL EXAMPLE
 Like Sub Contracting in real world, basically delegating the creation of Objects
to expert Factories
 Orders in a restaurant are received by a Kitchen, then are assigned to Special
Chefs like Chinese, Indian, Continental.
 Continent animals [abstract factory], represent [concreate factory] like Africa
animals which have [abstract product] like Carnivore animals represented by
[product] like lion
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 14
7.1.2.FACTORY METHOD PATTERN
1. OVERVIEW
 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 is to creating objects as Template Method is to implementing
an algorithm and then delegates the creation details to subclasses that are
supplied by the client
2. WHEN TO USE
 A framework needs to standardize the architectural model for a range of
applications, but allow for individual applications to define their own domain
objects and provide for their instantiation
3. STRUCTURE
Product (interface - abstract class)
 Uses defines the interface of objects the factory method creates
 Eg. Page
ConcreteProduct
 implements the Product interface
 Eg. SkillsPage, EducationPage, ExperiencePage
Creator (interface - abstract class)
 declares the factory method, which returns an object of type Product
 Creator may also define a default implementation of the factory method
that returns a default ConcreteProduct object
 may call the factory method to create a Product object.
 Eg. Document
ConcreteCreator
 overrides the factory method to return an instance of ConcreteProduct.
 Eg. Report, Resume
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 15
4. CHECK LIST
 If you have an inheritance hierarchy that exercises polymorphism, consider
adding a polymorphic creation capability by defining a static factory method
in the base class.
 Design the arguments to the factory method. What qualities or characteristics
are necessary and sufficient to identify the correct derived class to instantiate?
 Consider making all constructors private or protected.
5. CONCEPTUAL EXAMPLE
 Injection molding process demonstrate this pattern.
 Manufacturers of plastic toys process plastic molding powder, and inject the
plastic into molds of the desired shapes.
 The class of toy (car, action figure, etc.) is determined by the mold.
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 16
7.1.3.BUILDER PATTERN
1. OVERVIEW
 Builder pattern builds a complex object using simple objects and using a step
by step approach
 separate the construction of a complex object from its representation. By
doing so the same construction process can create different representations
2. WHEN TO USE
 create the elements of a complex aggregate. The specification for the
aggregate exists on secondary storage and one of many representations
needs to be built in primary storage.
 Parse a complex representation, create one of several targets
3. STRUCTURE
Builder (interface - abstract class)
 specifies an abstract interface for creating parts of a Product object
 Eg. VehicleBuilder
ConcreteBuilder
 constructs and assembles parts of the product by implementing the
Builder interface
 defines and keeps track of the representation it creates
 provides an interface for retrieving the product
 Eg. (MotorCycleBuilder, CarBuilder, ScooterBuilder)
Director
 constructs an object using the Builder interface, use concreate builder
 Eg. Shop
Product
 represents the complex object under construction. ConcreteBuilder
builds the product's internal
 representation and defines the process by which it's assembled
 includes classes that define the constituent parts, including interfaces
for assembling the parts into the final result
 Eg. Vehicle
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 17
4. CHECK LIST
 Decide if a common input and many possible representations (or outputs) is
the problem at hand
 Encapsulate the parsing of the common input in a Director class.
 Design a standard protocol for creating all possible output representations.
Capture the steps of this protocol in a Builder interface.
 Define a Builder derived class for each target representation.
 The client calls a Director object and create a Builder object,
 The client asks the Builder to return the result
5. CONCEPTUAL EXAMPLE
 Toy Builder build toy in construction process
[ build head – build body – build leg – build tail – build arm]
 Drink builder in construction process
[ add water – add sugar – add milk – add powder (tea, coffee)]
 Meal Builder in construction process
[main item – side item – drink – toy – Package]
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 18
7.1.4.PROTOTYPE PATTERN
1. OVERVIEW
 Specify the kinds of objects to create using a prototypical instance, and create
new objects by copying this prototype.
 Purpose to make dynamic creation easier by defining classes whose objects
can create duplicates of themselves
2. WHEN TO USE
 avoid the inherent cost of creating a new object in the standard way 'new'
keyword
 Sometimes, it becomes necessary to copy or clone an “already grown” object
rather than instantiating it and setting its values.
 Hides the complexities of making new instances from the client.
 In certain circumstances, copy an object is more efficient than creating a new
object
 Using a Prototype design pattern hides concrete product classes from the
client
3. STRUCTURE
Prototype (abstract class)
 declares an interface for cloning itself
 specifies a pure virtual clone () method
 Eg. ColorPrototype
Concrete Prototype (normal class)
 implements an operation for cloning itself
 Eg. Color
Client
 creates a new object by asking a prototype to clone itself
 Eg. ColorManager
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 19
4. CHECK LIST
 Add a clone () method to the existing "product" hierarchy.
 Design a "registry" that maintains a cache of prototypical objects. The registry
could be encapsulated in a new Factory class, or in the base class of the
"product" hierarchy.
 finds the correct prototype object, calls clone () on that object, and returns
the result.
 The client replaces all references to the new operator with calls to the factory
method.
5. CONCEPTUAL EXAMPLE
 Cell Division process by which a parent cell divides into two or more daughter
cells. [ identical cells] Cell division usually occurs as part of a larger cell cycle.
[the cell clones itself]
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 20
7.1.5.SINGLETON PATTERN
1. OVERVIEW
 one of the most commonly used design patterns
 Ensure a class has only one instance, and provide a global point of access to it
 By having a private default constructor for the class, other classes are not
allowed to instantiate a new object of the class
 static instance class level method is used to manage the creation of the object
2. WHEN TO USE
 Application needs one, and only one, instance of an object.
 lazy initialization and global access are necessary.
 prevents memory duplication
 saves system resources
 you can be sure that there is only one flow path for a certain task or data, this
result in more controlled and secure application work flow as well as easier
debugging and maintenance
 Ownership of the single instance cannot be reasonably assigned
3. STRUCTURE
Singleton (normal class)
 Have static property instant
 Make constructor private
 method that creates a new instance of the class if one does not exist. If
an instance already exists, it simply returns a reference to that object.
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 21
4. CHECK LIST
 Define a private static attribute in the "single instance" class.
 Define a public static accessor function in the class.
 Do "lazy initialization" (creation on first use) in the accessor function.
 Define all constructors to be protected or private.
 Clients may only use the accessor function to manipulate the Singleton.
5. CONCEPTUAL EXAMPLE
 Logger Class: 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.
 Configuration Classes: Singleton not only that we provide a global access
point, but we also keep the instance we use as a cache object
 Conceptual Teacher Example: using the Singleton pattern, there is one
Teacher and then each Student object receives a reference of that Teacher.
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 22
7.2. STRUCTURE PATTERNS
Structure patterns are design pattern than ease the design by identifying a
simple way to realize relationships between entities.
There are basic 7 pattern for structure pattern as follows
PATTERN DESCRIPTION Freq.
of use
Facade A single class that represents an entire subsystem 5/5
Adapter Match interfaces of different classes 4/5
Composite A tree structure of simple and composite objects 4/5
Bridge Separates an object’s interface from its implementation 3/5
Decorator Add responsibilities to objects dynamically 3/5
Flyweight A fine-grained instance used for efficient sharing 1/5
Proxy An object representing another object 4/5
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 23
7.2.1. FACADE PATTERN
1. OVERVIEW
 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
 Wrap a complicated subsystem with a simpler interface.
 commonly used with object-oriented programming.
 A facade is an object that provides a simplified interface to a larger body of
code, such as a class library.
2. WHEN TO USE
 A segment of the client community needs a simplified interface to the overall
functionality of a complex subsystem
 when a system is very complex or difficult to understand because the system
has a large number of interdependent classes or its source code is unavailable
 when you need to hide the complexities of the larger system and provides a
simpler interface to the client. (hide implementation details)
 when you need an entry point to each level of layered software
3. STRUCTURE
Facade (normal class)
The facade class abstracts Packages 1, 2, and 3 from the rest of the application.
Clients
The objects are using the Facade Pattern to access resources from the Packages.
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 24
4. CHECK LIST
 Identify a simpler, unified interface for the subsystem or component.
 Design a 'wrapper' class that encapsulates the subsystem.
 The facade/wrapper captures the complexity and collaborations of the
component, and delegates to the appropriate methods.
 The client uses (is coupled to) the Facade only.
 Consider whether additional Facades would add value.
5. CONCEPTUAL EXAMPLE
 The customer service representative acts as a Facade
 Make Pizza acts as facade represent pizza component cheese, sauce, etc.
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 25
7.2.2.ADAPTER PATTERN
1. OVERVIEW
 An adapter helps two incompatible interfaces to work together
 Allows the interface of an existing class to be used from another interface.
 It is often used to make existing classes work with others without modifying
their source code
 Interfaces may be incompatible but the inner functionality should suit the
need
2. WHEN TO USE
 An "off the shelf" component offers compelling functionality that you would
like to reuse, but its "view of the world" is not compatible with the philosophy
and architecture of the system currently being developed.
 allows incompatible classes to work together by converting the interface of
one class into an interface expected by the clients
3. STRUCTURE
Client:
Collaborates with objects conforming to the Target interface (eg. computer)
Target:
Defines the domain-specific interface that Client uses (eg. USB interface)
Adapter:
Adapts the interface Adaptee to the Target interface. (eg. PS/2 – USB adapter)
Adaptee:
Defines an existing interface that needs adapting (eg. PS/2 Mouse)
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 26
4. CHECK LIST
 Identify the players: the component(s) that want to be accommodated (i.e. the
client), and the component that needs to adapt (i.e. the adaptee).
 Identify the interface that the client requires.
 Design a "wrapper" class that can compatible the adaptee to the client.
 The adapter/wrapper class "has a" instance of the adaptee class.
 The adapter/wrapper class "maps" the client interface to the adaptee
interface.
 The client uses (is coupled to) the new interface
5. CONCEPTUAL EXAMPLE
 Old mouse with PS/2 Port use USB adaptor to send data to computer USB
 A man speaks Arabic need English translator adaptor to speak to English man
 2 phase plug need adapter to send signal to 3 phase socket
 Sata converter in hard disk
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 27
7.2.3.COMPOSITE PATTERN
1. OVERVIEW
 Composite pattern allows you to compose objects into tree structures to
represent part-whole hierarchies
 Composite lets clients treat individual objects and compositions of objects
uniformly [same way]
 Directories contain entries, each of which could be a directory
 Composite Like Menu – menu item tree structure
2. WHEN TO USE
 Application needs to manipulate a hierarchical collection of "primitive" and
"composite" objects
 Processing of a primitive object is handled one way, and processing of a
composite object is handled differently and its needed to be uniformly
3. STRUCTURE
Component:
 The abstraction for all components, including composite ones
 Declares the interface for objects in the composition
 [Optional] defines an interface for accessing a component's parent in the
recursive structure
Leaf:
 Represents leaf objects in the composition
 Implements all Component methods
Composite:
 Represents a composite Component (component having children)
 Implements methods to manipulate children
 Implements all Component methods, generally by delegating them to its
children
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 28
4. CHECK LIST
 Ensure that your problem is about representing "whole-part" relationships.
 Divide your domain concepts into container classes, and containee classes.
"Containers that contain containees, each of which could be a container"
 Create a "lowest common denominator" [component] interface that makes
your containers and containees interchangeable. It should specify the
behaviour that needs to be exercised uniformly across all containee and
container objects.
 All container and containee declare an "is a" relationship to the interface.
 All container declares a one-to-many "has a" relationship to the interface.
 Container leverage polymorphism to delegate to their containee objects.
 Child management methods [e.g. addChild (), removeChild ()] should normally
be defined in the Composite class
5. CONCEPTUAL EXAMPLE
 Family tree structure
 Work place organizational tree structure
 Directories tree structure files and child directories
 Menu that contain menu items, each could be menu
 Containers that contain elements, each could be containers
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 29
7.2.4.BRIDGE PATTERN
1. OVERVIEW
 Bridge decouple an abstraction from its implementation so that the two can
vary independently
 The bridge uses encapsulation, aggregation, and can use inheritance to
separate responsibilities into different classes.
 bridge pattern is often implemented using the class adapter pattern
 The bridge pattern can also be thought of as two layers of abstraction
2. WHEN TO USE
 decoupling the object's interface
 If you want to share an implementation among multiple objects
 If you want run-time binding of the implementation
 hiding details from clients
3. STRUCTURE
Abstraction (abstract class)
 defines the abstract interface
 maintains the Implementer reference.
 Eg. Shape abstract class
RefinedAbstraction (normal class)
 extends the interface defined by Abstraction
 Eg. Rectangle class
Implementor (interface)
 defines the interface for implementation classes
ImplementorA – ImplementorB (normal class)
 implements the Implementor interface
 Eg. Blue Implementer color
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 30
4. CHECK LIST
 Design a platform-oriented interface that is minimal, necessary, and sufficient.
Its goal is to decouple the abstraction from the platform
 Design the separation of concerns: what does the client want, and what do
the platforms provide
 Define a derived class of that interface for each platform
 Define specializations of the abstraction class if desired.
5. CONCEPTUAL EXAMPLE
 The purpose of the switch is to turn a device on or off
 The actual switch can be implemented as a pull chain, simple two position
switch, or a variety of dimmer switches
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 31
7.2.5.DECORATOR PATTERN
1. OVERVIEW
 Decorator pattern Allows behaviour to be added to an individual object,
either statically or dynamically, without affecting the behaviour of other
objects from the same class

2. WHEN TO USE
 Extend (decorate) the functionality of a certain object
 add behaviour or state to individual objects at run-time
3. STRUCTURE
Component (Interface)
 Defines the interface for objects that can have responsibilities added to
them dynamically
 Have members that will implemented by ConcreteComponent and
decorator
 Eg. Ice Cream abstract
ConcreteComponent (normal class)
 Define object to be decorated object to which additional responsibilities
can be attached to component.
 Eg. Chocolate, vanilla
Decorator (abstract class)
 maintains a reference to a Component object and defines an interface that
conforms to Component's interface
 act as base class for all decorators for components
 Eg. IceCream Topping "Add-ins"
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 32
ConcreteDecorator (normal class)
 override any Component method(s) whose behavior needs to be modified
 add additional responsibilities to the component
 Eg. Caramel
4. CHECK LIST
 Ensure the context is: a single core (or non-optional) component, several
optional decoration or wrappers, and an interface that is common to all
(Concreate Component)
 Create a "Lowest Common Denominator" interface that makes all classes
interchangeable (Component)
 Create a second level base class (Decorator) to support the wrapper classes.
 The Decorator class declares a composition relationship to the Component
interface, and this data member is initialized in its constructor
 The Decorator class delegates to the Component object.
 Define a Decorator derived class for each optional embellishment. (concreate
decorator)
 Decorator derived classes implement their wrapper functionality - and -
delegate to the Decorator base class
 The client configures the type and ordering of Core and Decorator objects
5. CONCEPTUAL EXAMPLE
 Ice cream (Component) with types like vanilla (Concrete Component) and
toppings (decorator) like caramel (Concreate decorator)
 Car (Component) with type like BMW (Concrete Component) and car
decorator can be petroleum or diesel (Concreate decorator)
 plain pizza need pizza decorator to make chicken pizza, veg pizza, etc.
 Weapon needs weapon decorator to add utilities to be advanced weapon
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 33
7.2.6.FLYWEIGHT PATTERN
1. OVERVIEW
 A flyweight is an object that minimizes memory use by sharing as much data
as possible with other similar objects
 it is a way to use objects in large numbers when a simple repeated
representation would use an unacceptable amount of memory.
 Flyweight is all about memory and sharing.
 There are two types of flyweight:
1. Intrinsic States are things that are constant and stored in the memory.
2. Extrinsic states are things that are not constant and needs to be calculated
on the fly and are therefore not stored in the memory.
2. WHEN TO USE
 Need to create large number of objects.
 Because of the large number when memory cost is a constraint.
 When most of the object attributes can be made external and shared.
3. STRUCTURE
Flyweight (Interface)
 declares an interface through which flyweights can receive and act on
extrinsic state
 Eg. Character
ConcreteFlyweight
 implements the Flyweight interface and adds storage for intrinsic state
 A ConcreteFlyweight object must be sharable
 Any state it stores must be intrinsic,
 Eg. (CharacterA, CharacterB, ..., CharacterZ)
UnsharedConcreteFlyweight
 not all Flyweight subclasses need to be shared
 The Flyweight interface enables sharing, but it doesn't enforce it
 Eg. Ice Cream abstract
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 34
FlyweightFactory
 creates and manages flyweight objects
 ensures that flyweight is shared properly.
 When a client requests a flyweight, the FlyweightFactory objects assets an
existing instance or creates one, if none exists.
 Eg. CharacterFactory
Client
 maintains a reference to flyweight(s).
 computes or stores the extrinsic state of flyweight(s).
 Eg. FlyweightApp
4. CHECK LIST
 Ensure that object overhead is an issue needing attention, and, the client of
the class is able and willing to absorb responsibility realignment.
 Divide the target class's state into: shareable (intrinsic) state, and non-
shareable (extrinsic) state
 Remove the non-shareable state from the class attributes, and add it the
calling argument list of affected methods
 Create a Factory that can cache and reuse existing class instances.
 client must use the Factory instead of the new operator to request objects.
 client must look-up or compute the non-shareable state, and supply that
state to class methods.
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 35
5. CONCEPTUAL EXAMPLE
 Angry bird application is the better example of flyweight pattern where
shape of bird is Intrinsic state while the color of the shape is Extrinsic state
 Modern web browsers use this technique to prevent loading same images
twice. When browser loads a web page, it traverses through all images on that
page. Browser loads all new images from Internet and places them the
internal cache. For already loaded images, a flyweight object is created, which
has some unique data like position within the page, but everything else is
referenced to the cached one.
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 36
7.2.7.PROXY PATTERN
1. OVERVIEW
 Provide a delegate or placeholder for another object to control access to it.
 proxy is a wrapper or agent object that is being called by the client to access
the real serving object behind the scenes
 For the client, usage of a proxy object is similar to using the real object,
because both implement the same interface.
 In the proxy extra functionality can be provided rather than real subject like
caching or check conditions before call real subject
2. WHEN TO USE
 you do not want to instantiate such objects unless and until they are actually
requested by the client. Like [protection proxy type]
 There are four common situations in which the Proxy pattern is applicable.
1. A virtual proxy:
placeholder for "expensive to create" objects. The real object is only
created when a client first requests/accesses the object
2. A remote proxy:
provides a local representative for an object that resides in a different
address space
3. A protective proxy:
controls access to a sensitive object. The "surrogate" object checks the
caller has the access permissions required prior to forwarding the request.
4. A smart proxy:
interposes additional actions when an object is accessed like
 Counting the number of references to the real object
 Loading a persistent object into memory when it's first referenced
 Checking that the real object is locked before it is accessed to
ensure that no other object can change it
3. STRUCTURE
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 37
Proxy (normal class)
 maintains a reference that lets the proxy access the real subject.
 provides an interface identical to Subject's so that a proxy can be
substituted for the real subject
 controls access to the real subject and may be responsible for creating and
deleting it
 Eg. Proxy Server - ATM
Subject (interface - abstract class)
 defines the common interface for RealSubject and Proxy so that a Proxy
can be used anywhere a RealSubject is expected.
 Eg. Server - Bank
RealSubject (normal class)
 defines the real object that the proxy represents.
 Eg. Web Server – DB Server – Concrete Bank
4. CHECK LIST
 Identify the leverage or "aspect" that is best implemented as a wrapper or
surrogate
 Define an interface that will make the proxy and the original component
interchangeable.
 The wrapper class holds a pointer to the real class and implements the
interface.
 The pointer may be initialized at construction, or on first use.
 Each wrapper method contributes its leverage, and delegates to the wrappee
object.
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 38
5. CONCEPTUAL EXAMPLE
 ATM Machine represent as proxy between customer who need to make
transaction and the bank [real subject]
 Proxy server in internet represent proxy between client request and
destination server
 Check represented as proxy between customer and real fund account
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 39
4.3. BEHAVIOUR PATTERNS
Behavioural design patterns are design patterns that identify common
communication patterns between objects and realize these patterns.
There are basic 12 pattern for behavioural pattern as follows
PATTERN DESCRIPTION Freq.
of use
Command Encapsulate a command request as an object 4/5
Chain
of responsibilities
A way of passing a request between a chain of objects 2/5
Interpreter A way to include language elements in a program 1/5
Iterator Sequentially access the elements of a collection 5/5
Mediator Defines simplified communication between classes 2/5
Memento Capture and restore an object's internal state 1/5
Null Object Designed to act as a default value of an object 4/5
Observer A way of notifying change to a number of classes 5/5
State Alter an object's behaviour when its state changes 3/5
Strategy Encapsulates an algorithm inside a class 4/5
Template Method Defer the exact steps of an algorithm to a subclass 3/5
Visitor Defines a new operation to a class without change 1/5
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 40
4.3.1. COMMAND PATTERN
1. OVERVIEW
 object is used to encapsulate all information needed to perform an action or
trigger an event at a later time
 This information includes the method name, the object that owns the method
and values for the method parameters.
 terms associated with command are command, receiver, invoker and client
 An object-oriented call-back
2. WHEN TO USE
 Need to issue requests to objects without knowing anything about the
operation being requested or the receiver of the request.
 Command objects are useful for implementing
GUI buttons and menu items Macro recording
Mobile Code Multi-level undo
Networking Progress bars
Parallel Processing Thread pools
Transactional behaviour Wizards
3. STRUCTURE
Command (normal class)
 declares an interface for executing an operation
 Eg. ICommand
ConcreteCommand (normal class)
 defines a binding between a Receiver object and an action
 implements Execute by invoke the corresponding operation(s) on Receiver
 Eg. LightOn, LightOff, AirConditionerOn, ConditionerOff
Client (normal class)
 creates a ConcreteCommand object and sets its receiver
 Eg. User
Invoker (normal class)
 asks the command to carry out the request
 Eg. RemoteController
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 41
Receiver (normal class)
 how to perform the operations associated with carrying out the request.
 Eg. AirConditioner, Light
4. CHECK LIST
 Define a Command interface with a method signature like execute ()
 Create one or more derived classes that encapsulate some subset of the
following: a "receiver" object, the method to invoke, the arguments to pass.
 Instantiate a Command object for each deferred execution request.
 Pass Command object from the creator (sender) to the invoker (receiver)
 The invoker decides when to execute ().
5. CONCEPTUAL EXAMPLE
 The customer (client) request order from waiter (invoker) he places the order
(command) and the order send to cook (Receiver)
 Client click menu item open (invoker) this will call open (command) and this
command will execute open file (receiver).
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 42
4.3.2. CHAIN OF RESPONSIBILITES PATTERN
1. OVERVIEW
 consisting of a source of command objects and a series of processing objects
 Each processing object contains logic that defines the types of command
objects that it can handle
 The rest are passed to the next processing object in the chain
 Chain the receiving objects and pass the request along the chain until an
object handles it.
 An object-oriented linked list with recursive traversal.
2. WHEN TO USE
 There is a potentially variable number of "handler" or "processing element" or
"node" objects, and a stream of requests that must be handled. Need to
efficiently process the requests without hard-wiring handler relationships and
precedence, or request-to-handler mappings.
 receiving objects together, and then passes any request messages from
object to object until it reaches an object capable of handling the message
3. STRUCTURE
Handler (abstract class)
 defines an interface for handling the requests
 (optional) implements the successor link
 Eg. Approver
ConcreteHandler (normal class)
 handles request it is responsible for
 can access its successor
 if the ConcreteHandler can handle the request, it does so; otherwise it
forwards the request to its successor
 Eg. (Director, Vice-president, President
Client (normal class)
 initiates the request to a ConcreteHandler object on the chain
 Eg. ChainApp
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 43
4. CHECK LIST
 The base class maintains a "next" pointer.
 Each derived class implements its contribution for handling the request.
 If the request needs to be "passed on", then the derived class "calls back" to
the base class, which delegates to the "next" pointer.
 The client (or some third party) creates and links the chain (which may include
a link from the last node to the root node).
 The client "launches and leaves" each request with the root of the chain.
 Recursive delegation produces the illusion of magic.
5. CONCEPTUAL EXAMPLE
 Question flow represent one person handle the request and answer the
question, if the first one know he won't ask the next one
 The Chain of Responsibility pattern avoids coupling the sender of a request to
the receiver by giving more than one object a chance to handle the request.
ATM use the Chain of Responsibility in money giving mechanism.
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 44
4.3.3. INTERPRETER PATTERN
1. OVERVIEW
 The interpreter design pattern provides way to evaluate language grammar or
expression. This pattern is used in sql parsing, symbol processing engine etc.
 Interpreter involves implementing an expression interface which tells to
interpret a particular context.
2. WHEN TO USE
 parsing light expressions defined in simple grammars and sometimes in
simple rule engines.
 Interpreter pattern only in terms of formal grammars but in this area there are
better solutions and this is the reason why this pattern is not so frequently
used
3. STRUCTURE
AbstractExpression (abstract class)
 declares an interface for executing an operation
 Eg. Expression
TerminalExpression
 implements Interpret operation related to terminal symbols in grammar.
 an instance is required for every terminal symbol in the sentence.
 Eg. (ThousandExpression, HundredExpression, TenExpression,
OneExpression)
NonterminalExpression
 defines an interface for handling the requests
 (optional) implements the successor link
 Eg. Approver
Context
 contains information that is global to the interpreter
 Eg. Context
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 45
Client
 builds an abstract syntax tree representing a particular sentence in the
language that the grammar defines, this will be assembled from instances
of the NonterminalExpression and TerminalExpression classes
 invokes the Interpret operation
 Eg. InterperterApp
4. CHECK LIST
 Decide if a "little language" offers a justifiable return on investment.
 Define a grammar for the language.
 Map each production in the grammar to a class.
 Organize the suite of classes into the structure of the Composite pattern.
 Define an interpret(Context) method in the Composite hierarchy.
 Context object encapsulates the current state of the input and output as the
former is parsed and the latter is accumulated. It is manipulated by each
grammar class as the "interpreting" process transforms input into output.
5. CONCEPTUAL EXAMPLE
 Date interpreter in have multiple date expression and it can receive logic date
context format and interpret it to readable format
 Google translate is example of interpreter it read the input language and
interpreted into other language
 Musicians are examples of Interpreters. Tone of a sound and its duration can
be represented in musical notation on a staff. This notation provides the
language of music. Musicians playing the music from the score are able to
reproduce the original tone and duration of each sound represented.
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 46
4.3.4. ITERATOR PATTERN
1. OVERVIEW
 The iterator pattern is a design pattern in which an iterator is used to traverse a
container and access the container's elements
 Provide a way to access the elements of an aggregate object sequentially without
exposing its underlying representation.
 .NET Framework has special interfaces that support a simple iteration:
[System.Collections.IEnumerator] over a non-generic collection and
System.Collections. Generic.IEnumerator<T> over a generic collection.

2. WHEN TO USE
 Need to "abstract" the traversal of wildly different data structures so that algorithms
can be defined that are capable of interfacing with each transparently.
1. STRUCTURE
Iterator (abstract class – interface)
 defines an interface for accessing and traversing elements.
 Has abstract Traversing operation (first, next, isDone, currentitem)
 Eg. Iterator
ConcreteIterator
 implements the Iterator interface.
 keeps track of the current position in the traversal of the aggregate.
 Eg. FacebookIterator – TwitterIterator both represent iterator
Aggregate (abstract class – interface)
 defines an interface for creating an Iterator object
 Eg. ISocialNetorking
ConcreteAggregate
 implements the Iterator creation interface to return an instance of the proper
ConcreteIterator
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 47
 Eg. Facebook (include user array), twitter (include user linkedlist)
2. CHECK LIST
 Add a create_iterator () method to the "collection" class, and grant the
"iterator" class privileged access.
 Design an "iterator" class that can encapsulate traversal of the "collection"
class.
 Clients ask the collection object to create an iterator object.
 Clients use the first (), is_done (), next (), andcurrent_item () protocol to access
the elements of the collection class.
3. CONCEPTUAL EXAMPLE
 In office settings where access to files is made through administrative or
secretarial staff, the Iterator pattern is demonstrated with the secretary acting
as the Iterator, To the executive, the filing system is confusing and illogical,
but the secretary is able to access files quickly and efficiently.
 On early television sets, a dial was used to change channels. When channel
surfing, the viewer was required to move the dial through each channel
position, regardless of whether or not that channel had reception.
On modern television sets, a next and previous button are used. When the
viewer selects the "next" button, the next tuned channel will be displayed
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 48
4.3.5. MEDIATOR PATTERN
1. OVERVIEW
 The mediator is the communication centre of the objects.
 When an object needs to communicate to another object, it doesn’t call the
other object directly. Instead it calls the mediator object which is to route the
communication to the destination object.
 Ensures that the components are loosely coupled, such that they don't call
each other explicitly; rather they always use a separate Mediator
implementation to do those jobs
2. WHEN TO USE
 reduce communication complexity between multiple objects or classes
 design reusable components, organize dependency between reusable pieces
and avoid spaghetti code
 reduce coupling between objects
3. STRUCTURE
Mediator (abstract class - interface)
 Defines an interface for communicating with Colleague objects
 Eg. IChatRoom
Concrete Mediator
 implements cooperative behaviour by coordinating Colleague objects
 knows and maintains its colleagues
 Eg. Chatroom
Colleague classes
 each Colleague class knows its Mediator object
 each colleague communicates with its mediator whenever it would have
otherwise communicated with another colleague
 Eg. Participant
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 49
4. CHECK LIST
 Identify a collection of interacting objects that would benefit from mutual
decoupling.
 Encapsulate those interactions in the abstraction of a new class.
 Create an instance of that new class and rework all "peer" objects to interact
with the Mediator only.
 Balance the principle of decoupling with the principle of distributing
responsibility evenly.
 Be careful not to create a "controller" object.
5. CONCEPTUAL EXAMPLE
 Chat room represent mediator between people need to contact to each other
 Facebook group represent mediator between users join it if anything updated
it will route to all registered users
 In Air Traffic Control (ATC) mediator, the pilots of the planes approaching or
departing the terminal area communicate with the tower rather than explicitly
communicating with one another
 The constraints on who can take off or land are enforced by the tower.
 It is important to note that the tower does not control the whole flight. It
exists only to enforce constraints in the terminal area.
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 50
4.3.6. MOMENTO PATTERN
1. OVERVIEW
 The Memento captures and externalizes an object's internal state so that the
object can later be restored to that state
2. WHEN TO USE
 Need to restore an object back to its previous state (e.g. "undo" or "rollback"
operations).
3. STRUCTURE
Memento (abstract class - interface)
 Defines an interface for communicating with Colleague objects
 the lock box that is written and read by the Originator, and derived by the
Caretaker
 Eg. Memento
Originator
 creates a memento containing a snapshot of its current internal state.
 uses the memento to restore its internal state
 the object that knows how to save itself.
 Eg. Sales Prospect
Caretaker
 is responsible for the memento's safekeeping
 never operates on or examines the contents of a memento.
 the object that knows why and when the Originator needs to save and restore
itself.
 Eg. Caretaker
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 51
4. CHECK LIST
 Identify the roles of “caretaker” and “originator”.
 Create a Memento class and declare the originator a friend.
 Caretaker knows when to "check point" the originator.
 Originator creates a Memento and copies its state to that Memento.
 Caretaker holds on to (but cannot peek into) the Memento.
 Caretaker knows when to "roll back" the originator.
 Originator reinstates itself using the saved state in the Memento.
5. CONCEPTUAL EXAMPLE
 Mechanics repairing drum brakes on their cars. The drums are removed from
both sides, exposing both the right and left brakes.
 Only one side is disassembled and the other serves as a Memento of how the
brake parts fit together.
 Only after the job has been completed on one side is the other side
disassembled.
 When the second side is disassembled, the first side acts as the Memento.
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 52
4.3.7. NULL OBJECT PATTERN
1. OVERVIEW
 Null Object is an object with no referenced value or with defined neutral
("null") behaviour.
 The Null Object design pattern describes the uses of such objects and their
behaviour
2. WHEN TO USE
references may be null. These references need to be checked to ensure they are
not null before invoking any methods, because methods typically cannot be
invoked on null references
3. STRUCTURE
Client
 declares an interface for executing an operation
AbstractObject
 declares the interface for Client's collaborator
 implements default behaviour for the interface common to all classes, as
appropriate
RealObject
 defines a concrete subclass of AbstractObject whose instances provide useful
behaviour that Client expects
NullObject
 provides an interface identical to Abstract Object's so that a null object can be
substituted for a real object
 implements its interface to do nothing What exactly it means to do nothing
depends on what sort of behaviour Client is expecting
 when there is more than one way to do nothing, more than one NullObject
class may be required
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 53
4. CHECK LIST
 Create abstract class that defines the interface for all objects of this type
 Create Null Object is implemented as a subclass of this abstract class
5. CONCEPTUAL EXAMPLE
 N/A
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 54
4.3.8. OBSERVER PATTERN
1. OVERVIEW
 Define a one-to-many dependency between objects so that when one object
changes state, all its dependents are notified and updated automatically.
 Observer pattern is also a key part in the familiar model–view–controller
(MVC) architectural pattern
2. WHEN TO USE
 the change of a state in one object must be reflected in another object
without keeping the objects tight coupled.
 the framework we are writing needs to be enhanced in future with new
observers with minimal changes.
3. STRUCTURE
Subject
 Any number of Observer objects may observe a subject
 provides an interface for attaching and detaching Observer objects.
 Eg. Stock
Concrete Subject
 stores state of interest to Concrete Observer
 sends a notification to its observers when its state changes
 Eg. IBM
Observer
 Defines an updating interface for objects that should be notified of changes
in a subject.
 Eg. IInvestor
Concrete Observer
 maintains a reference to a Concrete Subject object
 stores state that should stay consistent with the subject's
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 55
 implements the Observer updating interface to keep its state consistent with
the subject's
 Eg. Investor
4. CHECK LIST
 Differentiate between the core (or independent) functionality and the optional
(or dependent) functionality.
 Model the independent functionality with a "subject" abstraction.
 Model the dependent functionality with an "observer" hierarchy.
 The Subject is coupled only to the Observer base class.
 The client configures the number and type of Observers.
 Observers register themselves with the Subject.
 The Subject broadcasts events to all registered Observers.
 The Subject may "push" information at the Observers, or, the Observers may
"pull" the information they need from the Subject
5. CONCEPTUAL EXAMPLE
 Example 1: News Agency
 A news agency gathers news and publish them to different subscribers.
 We need to create a framework for and agency to be able to inform
immediately, when event occurs, its subscribers about the event.
 The subscribers can receive the news in different ways: Emails, SMS
 Example 2: Some auctions
 Each bidder possesses a numbered paddle that is used to indicate a bid.
 The auctioneer starts the bidding, and "observes" when a paddle is raised
to accept the bid.
 The acceptance of the bid changes the bid price which is broadcast to all
of the bidders in the form of a new bid.
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 56
4.3.9. STATE PATTERN
1. OVERVIEW
 Allow an object to alter its behaviour when its internal state changes
 known as the objects for states pattern
 The object will appear to change its class.
 An object-oriented state machine
2. WHEN TO USE
 encapsulate varying behaviour for the same object based on its internal state.
 a cleaner way for object to change its behaviour at runtime without resorting
to large solid conditional statements and thus improve maintainability
3. STRUCTURE
Context
 defines the interface of interest to clients
 maintains instance of a ConcreteState subclass to defines the current state.
 Eg. Account
state (interface – abstract class)
 defines an interface for encapsulating the behavior associated with a
particular state of the Context.
 Eg. State
ConcreteState
 each subclass implements a behavior associated with a state of Context
 Eg. (RedState, SilverState, GoldState)
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 57
4. CHECK LIST
 Identify an existing class, or new class, that will serve as the "state machine"
from the client's perspective. That class is the "wrapper" class.
 Create a State base class that replicates the methods of the state machine
interface. Each method takes one additional parameter: an instance of the
wrapper class. The State base class specifies any useful "default" behavior.
 Create a State derived class for each domain state. These derived classes only
override the methods they need to override.
 The wrapper class maintains a "current" State object.
 All client requests to the wrapper class are simply delegated to the current
State object, and the wrapper object's this pointer is passed.
 The State methods change the "current" state in the wrapper object as
appropriate.
5. CONCEPTUAL EXAMPLE
 ATM has states like [no debit card] state and you can only insert card and
[has debit card] state you can do other multiple operations
 SLDC (software development lifecycle) are states of any application from
requirement to maintenance
 TV Remote control has states on, off and each state has set of operations
 Vending Machine has multiple status like [money not inserted, product not
selected] and [money inserted and product selected]
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 58
4.3.10. STRATEGY PATTERN
1. OVERVIEW
 Define a family of algorithms, encapsulate each one, and make them
interchangeable
 Strategy lets the algorithm vary independently from the clients that use it.
 Capture the abstraction in an interface, bury implementation details in derived
classes.
2. WHEN TO USE
 Help to activate [open-closed principle] should be open for extension, but
closed for modification
 If your system needs to dynamically select one of several algorithms.
 If your system in which there are many classes, then if you need dynamically
allows to choose a behavior use the strategy pattern
3. STRUCTURE
Context
 is configured with a ConcreteStrategy object
 maintains a reference to a Strategy object
 may define an interface that lets Strategy access its data.
 Eg. SortedList
Strategy (interface – abstract class)
 declares an interface common to all supported algorithms. Context uses this
interface to call the algorithm defined by a ConcreteStrategy
 Eg. Sort Strategy
ConcreteStrategy
 implements the algorithm using the Strategy interface
 Eg. (QuickSort, ShellSort, MergeSort)
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 59
4. CHECK LIST
 Identify an algorithm (i.e. a behavior) that the client would prefer to access
through a "flex point".
 Specify the signature for that algorithm in an interface.
 Bury the alternative implementation details in derived classes.
 Clients of the algorithm couple themselves to the interface.
5. CONCEPTUAL EXAMPLE
 Compress files may be done by two strategy compress using zip or using rar
then send result to client
 When customer purchase something from mall, he can choose to pay using
different strategies like credit cards, debit cards or cache
 When client need to go to airport he can choose from different transport
strategies like taxi, bus, metro, etc.
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 60
4.3.11. TEMPLATE METHOD PATTERN
1. OVERVIEW
 defines the program skeleton of an algorithm in a method
 let one redefine certain steps of an algorithm without changing the
algorithm's structure
 Base class declares algorithm 'placeholders', and derived classes implement
the placeholders.
 Base class is created that provides the basic steps of an algorithm design.
These steps are implemented using abstract methods. Later on, subclasses
change the abstract methods to implement real actions.
2. WHEN TO USE
 used in frameworks, where each implements the invariant parts of a domain's
architecture, leaving "placeholders" for customisation options
 Let subclasses implement (through method overriding) behavior that can vary
 Avoid duplication in the code
 Control at what point(s) sub classing is allowed
3. STRUCTURE
AbstractClass (interface – abstract class)
 defines abstract primitive operations that concrete subclasses define to
implement steps of an algorithm
 implements a template method defining the skeleton of an algorithm.
 The template method calls primitive operations as well as operations defined
in AbstractClass or those of other objects.
 Eg. DataObject
ConcreteClass
 implements the primitive operations to carry out subclass-specific steps of the
algorithm
 Eg. CustomerDataObject
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 61
4. CHECK LIST
 Examine the algorithm, and decide which steps are standard and which steps
are peculiar to each of the current classes.
 Define a new abstract base class to host the "don't call us, we'll call you"
framework.
 Move the shell of the algorithm (now called the "template method") and the
definition of all standard steps to the new base class.
 Define a placeholder or "hook" method in the base class for each step that
requires many different implementations. This method can host a default
implementation
 Invoke the hook method(s) from the template method.
 Each of the existing classes declares an "is-a" relationship to the new abstract
base class.
 Remove from the existing classes all the implementation details that have
been moved to the base class.
 The only details that will remain in the existing classes will be the
implementation details peculiar to each derived class.
5. CONCEPTUAL EXAMPLE
 Home builders use the Template Method when developing a new subdivision
 A typical subdivision consists of a limited number of floor plans with different
variations available for each
 Within a floor plan, the foundation, framing, plumbing, and wiring will be
identical for each house
 Other example is daily routine of a worker.
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 62
4.3.12. VISITOR PATTERN
1. OVERVIEW
 visitor design pattern is a way of separating an algorithm from an object
structure on which it operates.
 A practical result of this separation is the ability to add new operations to
existing object structures without modifying those structures.
 one way to follow the open/closed principle.
2. WHEN TO USE
 Similar operations have to be performed on objects of different types
grouped in a structure (a collection or a more complex structure).
 There are many distinct and unrelated operations needed to be performed.
Visitor pattern allows us to create a separate visitor concrete class for each
operation type and to separate operation implementation from the objects
structure.
 The object structure is not likely to be changed but is very probable to have
new operations which have to be added.
 Since the pattern separates the visitor (representing operations, algorithms,
behaviours) from the object structure it's very easy to add new visitors as long
as the structure remains unchanged.
3. STRUCTURE
Visitor (Visitor)
 declares a Visit operation for each class of concreteElement in object structure
 The operation's name and signature identifies the class that sends the Visit
request to the visitor That lets the visitor determine the concrete class of the
element being visited.
 Then the visitor can access the elements directly using its particular interface
 Eg. Visitor
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 63
ConcreteVisitor
 implements each operation declared by Visitor.
 Each operation implements a fragment of the algorithm defined for the
corresponding class or object in the structure.
 ConcreteVisitor provides the context for the algorithm and stores its local state.
 This state often accumulates results during the traversal of the structure.
 Eg. (IncomeVisitor, VacationVisitor)
Element
 defines an Accept operation that takes a visitor as an argument.
 Eg. Element
ConcreteElement
 implements an Accept operation that takes a visitor as an argument
 Eg. Employee
ObjectStructure
 can enumerate its elements
 may provide a high-level interface to allow the visitor to visit its elements
 may either be a Composite (pattern) or a collection such as a list or a set
 Eg. Employees
4. CHECK LIST
 Confirm that the current hierarchy (known as the Element hierarchy) will be
fairly stable and that the public interface of these classes is sufficient for the
access the Visitor classes will require. If these conditions are not met, then the
Visitor pattern is not a good match.
 Create a Visitor base class with a visit(ElementXxx)method for each Element
derived type.
 Add an accept(Visitor) method to the Element hierarchy. The implementation
in each Element derived class is always the same – accept (Visitor v) {v. visit
(this);}. Because of cyclic dependencies, the declaration of the Element and
Visitor classes will need to be interleaved.
 The Element hierarchy is coupled only to the Visitor base class, but the Visitor
hierarchy is coupled to each Element derived class. If the stability of the
Element hierarchy is low, and the stability of the Visitor hierarchy is high;
consider swapping the 'roles' of the two hierarchies.
 Create a Visitor derived class for each "operation" to be performed on
Element objects. visit () implementations will rely on the Element's public
interface.
 The client creates Visitor objects and passes each to Element objects by
calling accept ().
.NET – DESIGN PATTERNS
‫السعودي‬ ‫البريد‬
.NET – DESIGN PATTERN Page | 64
5. CONCEPTUAL EXAMPLE
 the operation of a taxi company. When a person calls a taxi company
(accepting a visitor), the company dispatches a cab to the customer. Upon
entering the taxi, the customer, or Visitor, is no longer in control of his or her
own transportation, the taxi (driver) is.

More Related Content

What's hot

CS8592 Object Oriented Analysis & Design - UNIT II
CS8592 Object Oriented Analysis & Design - UNIT IICS8592 Object Oriented Analysis & Design - UNIT II
CS8592 Object Oriented Analysis & Design - UNIT IIpkaviya
 
CS8592 Object Oriented Analysis & Design - UNIT IV
CS8592 Object Oriented Analysis & Design - UNIT IV CS8592 Object Oriented Analysis & Design - UNIT IV
CS8592 Object Oriented Analysis & Design - UNIT IV pkaviya
 
Devnology Back to School: Empirical Evidence on Modeling in Software Development
Devnology Back to School: Empirical Evidence on Modeling in Software DevelopmentDevnology Back to School: Empirical Evidence on Modeling in Software Development
Devnology Back to School: Empirical Evidence on Modeling in Software DevelopmentDevnology
 
10 ooad uml-13
10 ooad uml-1310 ooad uml-13
10 ooad uml-13Niit Care
 
OO Development 3 - Models And UML
OO Development 3 - Models And UMLOO Development 3 - Models And UML
OO Development 3 - Models And UMLRandy Connolly
 
Architectural views
Architectural viewsArchitectural views
Architectural viewsSaleem Khan
 
Arch06 1
Arch06 1Arch06 1
Arch06 1nazn
 
Software Design and Modularity
Software Design and ModularitySoftware Design and Modularity
Software Design and ModularityDanyal Ahmad
 
02 ooad uml-02
02 ooad uml-0202 ooad uml-02
02 ooad uml-02Niit Care
 
Object oriented sad-5 part i
Object oriented sad-5 part iObject oriented sad-5 part i
Object oriented sad-5 part iBisrat Girma
 
Function oriented design
Function oriented designFunction oriented design
Function oriented designVidhun T
 
4+1view architecture
4+1view architecture4+1view architecture
4+1view architecturedrewz lin
 
OO Development 5 - Analysis
OO Development 5 - AnalysisOO Development 5 - Analysis
OO Development 5 - AnalysisRandy Connolly
 
Abbott's Textual Analysis : Software Engineering 2
Abbott's Textual Analysis : Software Engineering 2Abbott's Textual Analysis : Software Engineering 2
Abbott's Textual Analysis : Software Engineering 2wahab13
 

What's hot (20)

Object oriented analysis and design unit- ii
Object oriented analysis and design unit- iiObject oriented analysis and design unit- ii
Object oriented analysis and design unit- ii
 
CS8592 Object Oriented Analysis & Design - UNIT II
CS8592 Object Oriented Analysis & Design - UNIT IICS8592 Object Oriented Analysis & Design - UNIT II
CS8592 Object Oriented Analysis & Design - UNIT II
 
CS8592 Object Oriented Analysis & Design - UNIT IV
CS8592 Object Oriented Analysis & Design - UNIT IV CS8592 Object Oriented Analysis & Design - UNIT IV
CS8592 Object Oriented Analysis & Design - UNIT IV
 
Devnology Back to School: Empirical Evidence on Modeling in Software Development
Devnology Back to School: Empirical Evidence on Modeling in Software DevelopmentDevnology Back to School: Empirical Evidence on Modeling in Software Development
Devnology Back to School: Empirical Evidence on Modeling in Software Development
 
10 ooad uml-13
10 ooad uml-1310 ooad uml-13
10 ooad uml-13
 
Design engineering
Design engineeringDesign engineering
Design engineering
 
OO Development 3 - Models And UML
OO Development 3 - Models And UMLOO Development 3 - Models And UML
OO Development 3 - Models And UML
 
UML
UMLUML
UML
 
Jeet ooad unit-2
Jeet ooad unit-2Jeet ooad unit-2
Jeet ooad unit-2
 
Architectural views
Architectural viewsArchitectural views
Architectural views
 
Arch06 1
Arch06 1Arch06 1
Arch06 1
 
Software Design and Modularity
Software Design and ModularitySoftware Design and Modularity
Software Design and Modularity
 
Design UML diagrams
Design UML diagramsDesign UML diagrams
Design UML diagrams
 
02 ooad uml-02
02 ooad uml-0202 ooad uml-02
02 ooad uml-02
 
Object oriented sad-5 part i
Object oriented sad-5 part iObject oriented sad-5 part i
Object oriented sad-5 part i
 
Object oriented analysis and design unit- i
Object oriented analysis and design unit- iObject oriented analysis and design unit- i
Object oriented analysis and design unit- i
 
Function oriented design
Function oriented designFunction oriented design
Function oriented design
 
4+1view architecture
4+1view architecture4+1view architecture
4+1view architecture
 
OO Development 5 - Analysis
OO Development 5 - AnalysisOO Development 5 - Analysis
OO Development 5 - Analysis
 
Abbott's Textual Analysis : Software Engineering 2
Abbott's Textual Analysis : Software Engineering 2Abbott's Textual Analysis : Software Engineering 2
Abbott's Textual Analysis : Software Engineering 2
 

Viewers also liked

Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in javaGoogle
 
Design Pattern For C# Part 1
Design Pattern For C# Part 1Design Pattern For C# Part 1
Design Pattern For C# Part 1Shahzad
 
Developing an ASP.NET Web Application
Developing an ASP.NET Web ApplicationDeveloping an ASP.NET Web Application
Developing an ASP.NET Web ApplicationRishi Kothari
 
Web Design 101
Web Design 101Web Design 101
Web Design 101T.S. Lim
 
Introduction to .net framework
Introduction to .net frameworkIntroduction to .net framework
Introduction to .net frameworkArun Prasad
 

Viewers also liked (6)

Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Design Pattern For C# Part 1
Design Pattern For C# Part 1Design Pattern For C# Part 1
Design Pattern For C# Part 1
 
Developing an ASP.NET Web Application
Developing an ASP.NET Web ApplicationDeveloping an ASP.NET Web Application
Developing an ASP.NET Web Application
 
Web Design 101
Web Design 101Web Design 101
Web Design 101
 
Introduction to .net framework
Introduction to .net frameworkIntroduction to .net framework
Introduction to .net framework
 
Design Patterns (Examples in .NET)
Design Patterns (Examples in .NET)Design Patterns (Examples in .NET)
Design Patterns (Examples in .NET)
 

Similar to NET Design Patterns Guide

Module 2 design patterns-2
Module 2   design patterns-2Module 2   design patterns-2
Module 2 design patterns-2Ankit Dubey
 
Cs 1023 lec 9 design pattern (week 2)
Cs 1023 lec 9 design pattern (week 2)Cs 1023 lec 9 design pattern (week 2)
Cs 1023 lec 9 design pattern (week 2)stanbridge
 
Introduction to design patterns
Introduction to design patternsIntroduction to design patterns
Introduction to design patternsAmit Kabra
 
Generation of Automatic Code using Design Patterns
Generation of Automatic Code using Design PatternsGeneration of Automatic Code using Design Patterns
Generation of Automatic Code using Design PatternsIRJET Journal
 
5 Design Patterns Explained
5 Design Patterns Explained5 Design Patterns Explained
5 Design Patterns ExplainedPrabhjit Singh
 
SADP PPTs of all modules - Shanthi D.L.pdf
SADP PPTs of all modules - Shanthi D.L.pdfSADP PPTs of all modules - Shanthi D.L.pdf
SADP PPTs of all modules - Shanthi D.L.pdfB.T.L.I.T
 
Unit No 6 Design Patterns.pptx
Unit No 6 Design Patterns.pptxUnit No 6 Design Patterns.pptx
Unit No 6 Design Patterns.pptxDrYogeshDeshmukh1
 
(E book pdf) thinking in patterns with java
(E book   pdf) thinking in patterns with java(E book   pdf) thinking in patterns with java
(E book pdf) thinking in patterns with javaRaffaella D'angelo
 
Software Patterns
Software PatternsSoftware Patterns
Software Patternskim.mens
 
dotnet stuff.com tutorials-design-patterns_exploring-net-design-patterns-in-s...
dotnet stuff.com tutorials-design-patterns_exploring-net-design-patterns-in-s...dotnet stuff.com tutorials-design-patterns_exploring-net-design-patterns-in-s...
dotnet stuff.com tutorials-design-patterns_exploring-net-design-patterns-in-s...Anil Sharma
 
Sofwear deasign and need of design pattern
Sofwear deasign and need of design patternSofwear deasign and need of design pattern
Sofwear deasign and need of design patternchetankane
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design patternMindfire Solutions
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design PatternSanae BEKKAR
 
04 designing architectures
04 designing architectures04 designing architectures
04 designing architecturesMajong DevJfu
 
Design Patterns - General Introduction
Design Patterns - General IntroductionDesign Patterns - General Introduction
Design Patterns - General IntroductionAsma CHERIF
 

Similar to NET Design Patterns Guide (20)

Module 2 design patterns-2
Module 2   design patterns-2Module 2   design patterns-2
Module 2 design patterns-2
 
Cs 1023 lec 9 design pattern (week 2)
Cs 1023 lec 9 design pattern (week 2)Cs 1023 lec 9 design pattern (week 2)
Cs 1023 lec 9 design pattern (week 2)
 
Introduction to design patterns
Introduction to design patternsIntroduction to design patterns
Introduction to design patterns
 
Unit iii design patterns 9
Unit iii design patterns 9Unit iii design patterns 9
Unit iii design patterns 9
 
Patterns Overview
Patterns OverviewPatterns Overview
Patterns Overview
 
Generation of Automatic Code using Design Patterns
Generation of Automatic Code using Design PatternsGeneration of Automatic Code using Design Patterns
Generation of Automatic Code using Design Patterns
 
5 Design Patterns Explained
5 Design Patterns Explained5 Design Patterns Explained
5 Design Patterns Explained
 
SADP PPTs of all modules - Shanthi D.L.pdf
SADP PPTs of all modules - Shanthi D.L.pdfSADP PPTs of all modules - Shanthi D.L.pdf
SADP PPTs of all modules - Shanthi D.L.pdf
 
Unit No 6 Design Patterns.pptx
Unit No 6 Design Patterns.pptxUnit No 6 Design Patterns.pptx
Unit No 6 Design Patterns.pptx
 
(E book pdf) thinking in patterns with java
(E book   pdf) thinking in patterns with java(E book   pdf) thinking in patterns with java
(E book pdf) thinking in patterns with java
 
SA_UNIT_1.pptx
SA_UNIT_1.pptxSA_UNIT_1.pptx
SA_UNIT_1.pptx
 
Software Patterns
Software PatternsSoftware Patterns
Software Patterns
 
dotnet stuff.com tutorials-design-patterns_exploring-net-design-patterns-in-s...
dotnet stuff.com tutorials-design-patterns_exploring-net-design-patterns-in-s...dotnet stuff.com tutorials-design-patterns_exploring-net-design-patterns-in-s...
dotnet stuff.com tutorials-design-patterns_exploring-net-design-patterns-in-s...
 
Sofwear deasign and need of design pattern
Sofwear deasign and need of design patternSofwear deasign and need of design pattern
Sofwear deasign and need of design pattern
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design pattern
 
010821+presentation+oti.ppt
010821+presentation+oti.ppt010821+presentation+oti.ppt
010821+presentation+oti.ppt
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design Pattern
 
xCP Pattern Library 3.3
xCP Pattern Library 3.3xCP Pattern Library 3.3
xCP Pattern Library 3.3
 
04 designing architectures
04 designing architectures04 designing architectures
04 designing architectures
 
Design Patterns - General Introduction
Design Patterns - General IntroductionDesign Patterns - General Introduction
Design Patterns - General Introduction
 

More from Mohamed Zakarya Abdelgawad

EA foundations (Views, Repository, Artifacts and Metamodel)
EA foundations (Views, Repository, Artifacts and Metamodel)EA foundations (Views, Repository, Artifacts and Metamodel)
EA foundations (Views, Repository, Artifacts and Metamodel)Mohamed Zakarya Abdelgawad
 
Accenture/Insead Business Strategy Part 1 Certificate
Accenture/Insead Business Strategy Part 1 CertificateAccenture/Insead Business Strategy Part 1 Certificate
Accenture/Insead Business Strategy Part 1 CertificateMohamed Zakarya Abdelgawad
 
ITIL 4 Strategist Direct, Plan and Improve (DPI)
ITIL 4 Strategist Direct, Plan and Improve (DPI)ITIL 4 Strategist Direct, Plan and Improve (DPI)
ITIL 4 Strategist Direct, Plan and Improve (DPI)Mohamed Zakarya Abdelgawad
 
Architecture thinking w002 - Business Strategy Intro
Architecture thinking w002 - Business Strategy IntroArchitecture thinking w002 - Business Strategy Intro
Architecture thinking w002 - Business Strategy IntroMohamed Zakarya Abdelgawad
 

More from Mohamed Zakarya Abdelgawad (20)

EA foundations (Views, Repository, Artifacts and Metamodel)
EA foundations (Views, Repository, Artifacts and Metamodel)EA foundations (Views, Repository, Artifacts and Metamodel)
EA foundations (Views, Repository, Artifacts and Metamodel)
 
Mohammed Zakarya Resume
Mohammed Zakarya ResumeMohammed Zakarya Resume
Mohammed Zakarya Resume
 
Mohamed zakarya certificates
Mohamed zakarya certificatesMohamed zakarya certificates
Mohamed zakarya certificates
 
Mohammed Zakarya Resume
Mohammed Zakarya ResumeMohammed Zakarya Resume
Mohammed Zakarya Resume
 
EA foundations (views + repository)
EA foundations (views + repository)EA foundations (views + repository)
EA foundations (views + repository)
 
EA foundations - 01 (views & viewpoints)
EA foundations - 01 (views & viewpoints)EA foundations - 01 (views & viewpoints)
EA foundations - 01 (views & viewpoints)
 
Accenture/Insead Business Strategy Part 1 Certificate
Accenture/Insead Business Strategy Part 1 CertificateAccenture/Insead Business Strategy Part 1 Certificate
Accenture/Insead Business Strategy Part 1 Certificate
 
Dpbok context i
Dpbok   context iDpbok   context i
Dpbok context i
 
Digital Practitioner Capability Context
Digital Practitioner Capability ContextDigital Practitioner Capability Context
Digital Practitioner Capability Context
 
DPBOK Foundation
DPBOK FoundationDPBOK Foundation
DPBOK Foundation
 
Certified Microservice Archtiect
Certified Microservice ArchtiectCertified Microservice Archtiect
Certified Microservice Archtiect
 
Certified Business Architect
Certified Business ArchitectCertified Business Architect
Certified Business Architect
 
ITIL 4 Strategist Direct, Plan and Improve (DPI)
ITIL 4 Strategist Direct, Plan and Improve (DPI)ITIL 4 Strategist Direct, Plan and Improve (DPI)
ITIL 4 Strategist Direct, Plan and Improve (DPI)
 
Architecture thinking w002 - Business Strategy Intro
Architecture thinking w002 - Business Strategy IntroArchitecture thinking w002 - Business Strategy Intro
Architecture thinking w002 - Business Strategy Intro
 
Architecture thinking w001
Architecture thinking w001Architecture thinking w001
Architecture thinking w001
 
Business Architecture Foundations
Business Architecture FoundationsBusiness Architecture Foundations
Business Architecture Foundations
 
Togaf 9.2 Introduction
Togaf 9.2 IntroductionTogaf 9.2 Introduction
Togaf 9.2 Introduction
 
Discover Your IT Career Path
Discover Your IT Career PathDiscover Your IT Career Path
Discover Your IT Career Path
 
ITIL V4 Foundation
ITIL V4 FoundationITIL V4 Foundation
ITIL V4 Foundation
 
SOA foundation - Generation 2
SOA foundation - Generation 2SOA foundation - Generation 2
SOA foundation - Generation 2
 

Recently uploaded

GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 

Recently uploaded (20)

GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 

NET Design Patterns Guide

  • 1. .NET – DESIGN PATTERN VERSION (1.0) MOUDLE NAME .Net DESIGN PATTERN SUBMITTED FOR Saudi Post SUBMITTED BY ARCOM
  • 2. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 2 1. TABLE OF CONTENT 1. TABLE OF CONTENT ...................................................................................................................2 2. REVIEW HISTORY .......................................................................................................................4 2.1. STATUS ..........................................................................................................................................4 2.2. CHANGE HISTORY..........................................................................................................................4 2.3. DISTRIBUTION ...............................................................................................................................5 3. DOCUMENT PURPOSE................................................................................................................6 4. OBJECT-ORIENTED DESIGN PATTERNS .......................................................................................7 5. BASIC ELEMENTS OF A DESIGN PATTERN ...................................................................................8 6. DESIGN PATTERN STYLE GUIDE ..................................................................................................9 7. DESIGN PATTERN TYPES...........................................................................................................10 7.1. CREATIONAL PATTERNS...........................................................................................................11 7.1.1. ABSTRACT FACTORY PATTERN...............................................................................................12 7.1.2. FACTORY METHOD PATTERN.................................................................................................14 7.1.3. BUILDER PATTERN .................................................................................................................16 7.1.4. PROTOTYPE PATTERN............................................................................................................18 7.1.5. SINGLETON PATTERN.............................................................................................................20 7.2. STRUCTURE PATTERNS.............................................................................................................22 7.2.1. FACADE PATTERN ..................................................................................................................23 7.2.2. ADAPTER PATTERN................................................................................................................25 7.2.3. COMPOSITE PATTERN............................................................................................................27 7.2.4. BRIDGE PATTERN...................................................................................................................29 7.2.5. DECORATOR PATTERN...........................................................................................................31 7.2.6. FLYWEIGHT PATTERN ............................................................................................................33 7.2.7. PROXY PATTERN ....................................................................................................................36 4.3. BEHAVIOUR PATTERNS ............................................................................................................39 4.3.1. COMMAND PATTERN ............................................................................................................40 4.3.2. CHAIN OF RESPONSIBILITES PATTERN...................................................................................42 4.3.3. INTERPRETER PATTERN .........................................................................................................44 4.3.4. ITERATOR PATTERN ...............................................................................................................46 4.3.5. MEDIATOR PATTERN .............................................................................................................48 4.3.6. MOMENTO PATTERN.............................................................................................................50 4.3.7. NULL OBJECT PATTERN..........................................................................................................52 4.3.8. OBSERVER PATTERN ..............................................................................................................54
  • 3. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 3 4.3.9. STATE PATTERN .....................................................................................................................56 4.3.10. STRATEGY PATTERN...............................................................................................................58 4.3.11. TEMPLATE METHOD PATTERN ..............................................................................................60 4.3.12. VISITOR PATTERN ..................................................................................................................62
  • 4. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 4 2. REVIEW HISTORY 2.1.STATUS Version 1.0 Status Proposed 2.2.CHANGE HISTORY Date Author Version Change Reference 10/03/2016 Mohamed Zakarya 1.0 First draft
  • 5. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 5 2.3.DISTRIBUTION APPROVERS Stakeholder Name CONSULTED Stakeholder Name INFORMED Stakeholder Name Choose an item. Choose an item.
  • 6. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 6 3. DOCUMENT PURPOSE As we build more complex computer systems, we face problems of construction rather than problems of analysis. The problems of construction are solved by designing programming solutions for such problems in the context of the computer application we are trying to build. Some constructional problems occur over and over again across a wide range of different computer applications. Obviously, we can design a generic solution to such repeating problems, and then try to adjust such a generic solution to the specific need of the application we are currently building. Such generic solutions are usually referred to as design patterns. Christopher Alexander first introduced patterns to encode knowledge and experience in designing buildings. He said: “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 many times over, without ever doing it the same way twice”. Thus, a design pattern is the core of a solution to a problem in context. The solution can be applied in different situations, and has to be adapted to fit the needs of the specific situation.
  • 7. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 7 4. Object-Oriented Design Patterns Design patterns in programming were first introduced by the Gang of Four (Gamma, Helm, Johnson, Vlissides). They referred to design patterns always as to object-oriented design patterns, i.e., design patterns that occur in building object-oriented computer systems. Thus, object-oriented design patterns might be defined as descriptions of communicating objects and classes that are customized to solve a general (object- oriented) design problem in a particular context. They also stated that an object-oriented design pattern is not:  A primitive building block, such as linked lists, or hash-tables that can be encoded in classes and reused in a wide range of applications  A complex, domain specific design for an entire application or subsystem. Rather, an object-oriented design pattern just describes a recurring object- oriented design structure. Thus, an object-oriented design pattern:  Names, abstracts, and identifies the key aspect (classes, objects and their relations) of a common design structure  Creates a reusable object-oriented design  Focuses on a particular object-oriented design by describing when it applies, whether it can be applying in view of other design constraints, and the consequences and trade-offs of its use  Implements the design idea in an object-oriented programming language. In the rest of this paper we will examine solely object-oriented design patterns. Thus, whenever we say a design pattern we actually refer to an object-oriented design patter
  • 8. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 8 5. Basic Elements of a Design Pattern Each pattern has four essential elements:  The pattern name is a handle we can use to describe a design problem, its solutions and consequences in a word or two. Naming a pattern immediately increases the design vocabulary of programmers. Having a vocabulary for patterns enables to talk about patterns with other programmers, in the documentation, etc.  The problem describes when to apply the pattern. It explains the problem and its context. It might describe specific design problems such as how to represent algorithms as objects. It might describe class or object structures that are symptomatic of an inflexible design. Sometimes the problem includes also a list of conditions that must be met before it makes sense to apply the pattern.  The solution describes the elements that make up the design, their relationships, responsibilities, and collaborations. The solution doesn’t describe a particular concrete design or implementation, because a pattern is like a template that can be applied in many different situations. Instead, the pattern provides an abstract description of a design problem and how a general arrangement of elements (classes and objects) solves it.  The consequences are the results and trade-offs of applying the pattern. They may address language and implementation issues as well. Since reuse is often a factor in object-oriented design, the consequences of a pattern include its impact on a system’s flexibility, extensibility, or portability.
  • 9. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 9 6. DESIGN PATTERN STYLE GUIDE The description of any pattern will follow the next style guide: 1. OVERVIEW  Overview about the pattern 2. WHEN TO USE  What problem you face and when to user this pattern 3. STRUCTURE  Pattern structure 4. CHECK LIST  Check list when implement the pattern 5. CONCEPTUAL EXAMPLE  Real example of using pattern
  • 10. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 10 7. DESIGN PATTERN TYPES There is basic pattern that are foundation of other patterns they are categorized in three groups 1. Creational patterns 2. Structural patterns 3. Behavioural patterns CREATIONAL PATTERNS  create objects for you, rather than having you instantiate objects directly.  This gives your program more flexibility in deciding which objects need to be created for a given case. STRUCTURE PATTERNS  These concern class and object composition.  Identifying a simple way to realize relationships between entities.  They use inheritance to compose interfaces and define ways to compose objects to obtain new functionality. BEHAVIOUR PATTERNS  Identify common communication patterns between objects and realize these patterns.  These patterns increase flexibility in carrying out this communication.
  • 11. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 11 7.1. CREATIONAL PATTERNS Creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation There are basic 6 pattern for creational pattern as follows PATTERN DESCRIPTION Freq. of use Abstract factory Creates an instance of several families of classes 5/5 Factory Method Creates an instance of several derived classes 5/5 Builder Separates object construction from its representation 2/5 Prototype A fully initialized instance to be copied or cloned 3/5 Singleton A class of which only a single instance can exist 4/5
  • 12. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 12 7.1.1.ABSTRACT FACTORY PATTERN 1. OVERVIEW  Abstract Factory pattern is a super factory which creates other factories, this factory is called factory of factories  This pattern provides one of the best ways to create an object  Abstract Factory pattern an interface is responsible for encapsulate a group of individual factories that have a common theme without specifying their concrete classes 2. WHEN TO USE  The purpose of the Abstract Factory is to provide an interface for creating families of related objects, without specifying concrete classes  providing data access to two different data sources  supporting multiple platforms while keeping your code-base unified 3. STRUCTURE Client  Uses interfaces declared by AbstractFactory and AbstractProduct classes  Eg. Animal World AbstractFactory (abstract class)  declares an interface for operations that create abstract products  Eg. Continent Factory ConcreteFactory (normal class)  implements the operations to create concrete product objects  extend the abstract factory functionality  Eg. (AfricaFactory, AmericaFactory)
  • 13. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 13 AbstractProduct (interface – abstract class)  declares an interface for a type of product object  Eg. (Herbivore, Carnivore) Product (class)  defines a product to be created by the corresponding concrete factory  implements the AbstractProduct interface  Eg. Wildebeest, Lion, Bison, Wolf 4. CHECK LIST  Map out a matrix of "platforms" versus "products"  Define a factory interface that consists of a factory method per product.  Define a factory derived class for each platform that encapsulates all references to the new operator  The client should retire all references to new, and use the factory methods to create the product objects 5. CONCEPTUAL EXAMPLE  Like Sub Contracting in real world, basically delegating the creation of Objects to expert Factories  Orders in a restaurant are received by a Kitchen, then are assigned to Special Chefs like Chinese, Indian, Continental.  Continent animals [abstract factory], represent [concreate factory] like Africa animals which have [abstract product] like Carnivore animals represented by [product] like lion
  • 14. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 14 7.1.2.FACTORY METHOD PATTERN 1. OVERVIEW  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 is to creating objects as Template Method is to implementing an algorithm and then delegates the creation details to subclasses that are supplied by the client 2. WHEN TO USE  A framework needs to standardize the architectural model for a range of applications, but allow for individual applications to define their own domain objects and provide for their instantiation 3. STRUCTURE Product (interface - abstract class)  Uses defines the interface of objects the factory method creates  Eg. Page ConcreteProduct  implements the Product interface  Eg. SkillsPage, EducationPage, ExperiencePage Creator (interface - abstract class)  declares the factory method, which returns an object of type Product  Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object  may call the factory method to create a Product object.  Eg. Document ConcreteCreator  overrides the factory method to return an instance of ConcreteProduct.  Eg. Report, Resume
  • 15. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 15 4. CHECK LIST  If you have an inheritance hierarchy that exercises polymorphism, consider adding a polymorphic creation capability by defining a static factory method in the base class.  Design the arguments to the factory method. What qualities or characteristics are necessary and sufficient to identify the correct derived class to instantiate?  Consider making all constructors private or protected. 5. CONCEPTUAL EXAMPLE  Injection molding process demonstrate this pattern.  Manufacturers of plastic toys process plastic molding powder, and inject the plastic into molds of the desired shapes.  The class of toy (car, action figure, etc.) is determined by the mold.
  • 16. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 16 7.1.3.BUILDER PATTERN 1. OVERVIEW  Builder pattern builds a complex object using simple objects and using a step by step approach  separate the construction of a complex object from its representation. By doing so the same construction process can create different representations 2. WHEN TO USE  create the elements of a complex aggregate. The specification for the aggregate exists on secondary storage and one of many representations needs to be built in primary storage.  Parse a complex representation, create one of several targets 3. STRUCTURE Builder (interface - abstract class)  specifies an abstract interface for creating parts of a Product object  Eg. VehicleBuilder ConcreteBuilder  constructs and assembles parts of the product by implementing the Builder interface  defines and keeps track of the representation it creates  provides an interface for retrieving the product  Eg. (MotorCycleBuilder, CarBuilder, ScooterBuilder) Director  constructs an object using the Builder interface, use concreate builder  Eg. Shop Product  represents the complex object under construction. ConcreteBuilder builds the product's internal  representation and defines the process by which it's assembled  includes classes that define the constituent parts, including interfaces for assembling the parts into the final result  Eg. Vehicle
  • 17. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 17 4. CHECK LIST  Decide if a common input and many possible representations (or outputs) is the problem at hand  Encapsulate the parsing of the common input in a Director class.  Design a standard protocol for creating all possible output representations. Capture the steps of this protocol in a Builder interface.  Define a Builder derived class for each target representation.  The client calls a Director object and create a Builder object,  The client asks the Builder to return the result 5. CONCEPTUAL EXAMPLE  Toy Builder build toy in construction process [ build head – build body – build leg – build tail – build arm]  Drink builder in construction process [ add water – add sugar – add milk – add powder (tea, coffee)]  Meal Builder in construction process [main item – side item – drink – toy – Package]
  • 18. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 18 7.1.4.PROTOTYPE PATTERN 1. OVERVIEW  Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.  Purpose to make dynamic creation easier by defining classes whose objects can create duplicates of themselves 2. WHEN TO USE  avoid the inherent cost of creating a new object in the standard way 'new' keyword  Sometimes, it becomes necessary to copy or clone an “already grown” object rather than instantiating it and setting its values.  Hides the complexities of making new instances from the client.  In certain circumstances, copy an object is more efficient than creating a new object  Using a Prototype design pattern hides concrete product classes from the client 3. STRUCTURE Prototype (abstract class)  declares an interface for cloning itself  specifies a pure virtual clone () method  Eg. ColorPrototype Concrete Prototype (normal class)  implements an operation for cloning itself  Eg. Color Client  creates a new object by asking a prototype to clone itself  Eg. ColorManager
  • 19. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 19 4. CHECK LIST  Add a clone () method to the existing "product" hierarchy.  Design a "registry" that maintains a cache of prototypical objects. The registry could be encapsulated in a new Factory class, or in the base class of the "product" hierarchy.  finds the correct prototype object, calls clone () on that object, and returns the result.  The client replaces all references to the new operator with calls to the factory method. 5. CONCEPTUAL EXAMPLE  Cell Division process by which a parent cell divides into two or more daughter cells. [ identical cells] Cell division usually occurs as part of a larger cell cycle. [the cell clones itself]
  • 20. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 20 7.1.5.SINGLETON PATTERN 1. OVERVIEW  one of the most commonly used design patterns  Ensure a class has only one instance, and provide a global point of access to it  By having a private default constructor for the class, other classes are not allowed to instantiate a new object of the class  static instance class level method is used to manage the creation of the object 2. WHEN TO USE  Application needs one, and only one, instance of an object.  lazy initialization and global access are necessary.  prevents memory duplication  saves system resources  you can be sure that there is only one flow path for a certain task or data, this result in more controlled and secure application work flow as well as easier debugging and maintenance  Ownership of the single instance cannot be reasonably assigned 3. STRUCTURE Singleton (normal class)  Have static property instant  Make constructor private  method that creates a new instance of the class if one does not exist. If an instance already exists, it simply returns a reference to that object.
  • 21. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 21 4. CHECK LIST  Define a private static attribute in the "single instance" class.  Define a public static accessor function in the class.  Do "lazy initialization" (creation on first use) in the accessor function.  Define all constructors to be protected or private.  Clients may only use the accessor function to manipulate the Singleton. 5. CONCEPTUAL EXAMPLE  Logger Class: 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.  Configuration Classes: Singleton not only that we provide a global access point, but we also keep the instance we use as a cache object  Conceptual Teacher Example: using the Singleton pattern, there is one Teacher and then each Student object receives a reference of that Teacher.
  • 22. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 22 7.2. STRUCTURE PATTERNS Structure patterns are design pattern than ease the design by identifying a simple way to realize relationships between entities. There are basic 7 pattern for structure pattern as follows PATTERN DESCRIPTION Freq. of use Facade A single class that represents an entire subsystem 5/5 Adapter Match interfaces of different classes 4/5 Composite A tree structure of simple and composite objects 4/5 Bridge Separates an object’s interface from its implementation 3/5 Decorator Add responsibilities to objects dynamically 3/5 Flyweight A fine-grained instance used for efficient sharing 1/5 Proxy An object representing another object 4/5
  • 23. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 23 7.2.1. FACADE PATTERN 1. OVERVIEW  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  Wrap a complicated subsystem with a simpler interface.  commonly used with object-oriented programming.  A facade is an object that provides a simplified interface to a larger body of code, such as a class library. 2. WHEN TO USE  A segment of the client community needs a simplified interface to the overall functionality of a complex subsystem  when a system is very complex or difficult to understand because the system has a large number of interdependent classes or its source code is unavailable  when you need to hide the complexities of the larger system and provides a simpler interface to the client. (hide implementation details)  when you need an entry point to each level of layered software 3. STRUCTURE Facade (normal class) The facade class abstracts Packages 1, 2, and 3 from the rest of the application. Clients The objects are using the Facade Pattern to access resources from the Packages.
  • 24. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 24 4. CHECK LIST  Identify a simpler, unified interface for the subsystem or component.  Design a 'wrapper' class that encapsulates the subsystem.  The facade/wrapper captures the complexity and collaborations of the component, and delegates to the appropriate methods.  The client uses (is coupled to) the Facade only.  Consider whether additional Facades would add value. 5. CONCEPTUAL EXAMPLE  The customer service representative acts as a Facade  Make Pizza acts as facade represent pizza component cheese, sauce, etc.
  • 25. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 25 7.2.2.ADAPTER PATTERN 1. OVERVIEW  An adapter helps two incompatible interfaces to work together  Allows the interface of an existing class to be used from another interface.  It is often used to make existing classes work with others without modifying their source code  Interfaces may be incompatible but the inner functionality should suit the need 2. WHEN TO USE  An "off the shelf" component offers compelling functionality that you would like to reuse, but its "view of the world" is not compatible with the philosophy and architecture of the system currently being developed.  allows incompatible classes to work together by converting the interface of one class into an interface expected by the clients 3. STRUCTURE Client: Collaborates with objects conforming to the Target interface (eg. computer) Target: Defines the domain-specific interface that Client uses (eg. USB interface) Adapter: Adapts the interface Adaptee to the Target interface. (eg. PS/2 – USB adapter) Adaptee: Defines an existing interface that needs adapting (eg. PS/2 Mouse)
  • 26. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 26 4. CHECK LIST  Identify the players: the component(s) that want to be accommodated (i.e. the client), and the component that needs to adapt (i.e. the adaptee).  Identify the interface that the client requires.  Design a "wrapper" class that can compatible the adaptee to the client.  The adapter/wrapper class "has a" instance of the adaptee class.  The adapter/wrapper class "maps" the client interface to the adaptee interface.  The client uses (is coupled to) the new interface 5. CONCEPTUAL EXAMPLE  Old mouse with PS/2 Port use USB adaptor to send data to computer USB  A man speaks Arabic need English translator adaptor to speak to English man  2 phase plug need adapter to send signal to 3 phase socket  Sata converter in hard disk
  • 27. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 27 7.2.3.COMPOSITE PATTERN 1. OVERVIEW  Composite pattern allows you to compose objects into tree structures to represent part-whole hierarchies  Composite lets clients treat individual objects and compositions of objects uniformly [same way]  Directories contain entries, each of which could be a directory  Composite Like Menu – menu item tree structure 2. WHEN TO USE  Application needs to manipulate a hierarchical collection of "primitive" and "composite" objects  Processing of a primitive object is handled one way, and processing of a composite object is handled differently and its needed to be uniformly 3. STRUCTURE Component:  The abstraction for all components, including composite ones  Declares the interface for objects in the composition  [Optional] defines an interface for accessing a component's parent in the recursive structure Leaf:  Represents leaf objects in the composition  Implements all Component methods Composite:  Represents a composite Component (component having children)  Implements methods to manipulate children  Implements all Component methods, generally by delegating them to its children
  • 28. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 28 4. CHECK LIST  Ensure that your problem is about representing "whole-part" relationships.  Divide your domain concepts into container classes, and containee classes. "Containers that contain containees, each of which could be a container"  Create a "lowest common denominator" [component] interface that makes your containers and containees interchangeable. It should specify the behaviour that needs to be exercised uniformly across all containee and container objects.  All container and containee declare an "is a" relationship to the interface.  All container declares a one-to-many "has a" relationship to the interface.  Container leverage polymorphism to delegate to their containee objects.  Child management methods [e.g. addChild (), removeChild ()] should normally be defined in the Composite class 5. CONCEPTUAL EXAMPLE  Family tree structure  Work place organizational tree structure  Directories tree structure files and child directories  Menu that contain menu items, each could be menu  Containers that contain elements, each could be containers
  • 29. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 29 7.2.4.BRIDGE PATTERN 1. OVERVIEW  Bridge decouple an abstraction from its implementation so that the two can vary independently  The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.  bridge pattern is often implemented using the class adapter pattern  The bridge pattern can also be thought of as two layers of abstraction 2. WHEN TO USE  decoupling the object's interface  If you want to share an implementation among multiple objects  If you want run-time binding of the implementation  hiding details from clients 3. STRUCTURE Abstraction (abstract class)  defines the abstract interface  maintains the Implementer reference.  Eg. Shape abstract class RefinedAbstraction (normal class)  extends the interface defined by Abstraction  Eg. Rectangle class Implementor (interface)  defines the interface for implementation classes ImplementorA – ImplementorB (normal class)  implements the Implementor interface  Eg. Blue Implementer color
  • 30. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 30 4. CHECK LIST  Design a platform-oriented interface that is minimal, necessary, and sufficient. Its goal is to decouple the abstraction from the platform  Design the separation of concerns: what does the client want, and what do the platforms provide  Define a derived class of that interface for each platform  Define specializations of the abstraction class if desired. 5. CONCEPTUAL EXAMPLE  The purpose of the switch is to turn a device on or off  The actual switch can be implemented as a pull chain, simple two position switch, or a variety of dimmer switches
  • 31. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 31 7.2.5.DECORATOR PATTERN 1. OVERVIEW  Decorator pattern Allows behaviour to be added to an individual object, either statically or dynamically, without affecting the behaviour of other objects from the same class  2. WHEN TO USE  Extend (decorate) the functionality of a certain object  add behaviour or state to individual objects at run-time 3. STRUCTURE Component (Interface)  Defines the interface for objects that can have responsibilities added to them dynamically  Have members that will implemented by ConcreteComponent and decorator  Eg. Ice Cream abstract ConcreteComponent (normal class)  Define object to be decorated object to which additional responsibilities can be attached to component.  Eg. Chocolate, vanilla Decorator (abstract class)  maintains a reference to a Component object and defines an interface that conforms to Component's interface  act as base class for all decorators for components  Eg. IceCream Topping "Add-ins"
  • 32. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 32 ConcreteDecorator (normal class)  override any Component method(s) whose behavior needs to be modified  add additional responsibilities to the component  Eg. Caramel 4. CHECK LIST  Ensure the context is: a single core (or non-optional) component, several optional decoration or wrappers, and an interface that is common to all (Concreate Component)  Create a "Lowest Common Denominator" interface that makes all classes interchangeable (Component)  Create a second level base class (Decorator) to support the wrapper classes.  The Decorator class declares a composition relationship to the Component interface, and this data member is initialized in its constructor  The Decorator class delegates to the Component object.  Define a Decorator derived class for each optional embellishment. (concreate decorator)  Decorator derived classes implement their wrapper functionality - and - delegate to the Decorator base class  The client configures the type and ordering of Core and Decorator objects 5. CONCEPTUAL EXAMPLE  Ice cream (Component) with types like vanilla (Concrete Component) and toppings (decorator) like caramel (Concreate decorator)  Car (Component) with type like BMW (Concrete Component) and car decorator can be petroleum or diesel (Concreate decorator)  plain pizza need pizza decorator to make chicken pizza, veg pizza, etc.  Weapon needs weapon decorator to add utilities to be advanced weapon
  • 33. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 33 7.2.6.FLYWEIGHT PATTERN 1. OVERVIEW  A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects  it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory.  Flyweight is all about memory and sharing.  There are two types of flyweight: 1. Intrinsic States are things that are constant and stored in the memory. 2. Extrinsic states are things that are not constant and needs to be calculated on the fly and are therefore not stored in the memory. 2. WHEN TO USE  Need to create large number of objects.  Because of the large number when memory cost is a constraint.  When most of the object attributes can be made external and shared. 3. STRUCTURE Flyweight (Interface)  declares an interface through which flyweights can receive and act on extrinsic state  Eg. Character ConcreteFlyweight  implements the Flyweight interface and adds storage for intrinsic state  A ConcreteFlyweight object must be sharable  Any state it stores must be intrinsic,  Eg. (CharacterA, CharacterB, ..., CharacterZ) UnsharedConcreteFlyweight  not all Flyweight subclasses need to be shared  The Flyweight interface enables sharing, but it doesn't enforce it  Eg. Ice Cream abstract
  • 34. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 34 FlyweightFactory  creates and manages flyweight objects  ensures that flyweight is shared properly.  When a client requests a flyweight, the FlyweightFactory objects assets an existing instance or creates one, if none exists.  Eg. CharacterFactory Client  maintains a reference to flyweight(s).  computes or stores the extrinsic state of flyweight(s).  Eg. FlyweightApp 4. CHECK LIST  Ensure that object overhead is an issue needing attention, and, the client of the class is able and willing to absorb responsibility realignment.  Divide the target class's state into: shareable (intrinsic) state, and non- shareable (extrinsic) state  Remove the non-shareable state from the class attributes, and add it the calling argument list of affected methods  Create a Factory that can cache and reuse existing class instances.  client must use the Factory instead of the new operator to request objects.  client must look-up or compute the non-shareable state, and supply that state to class methods.
  • 35. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 35 5. CONCEPTUAL EXAMPLE  Angry bird application is the better example of flyweight pattern where shape of bird is Intrinsic state while the color of the shape is Extrinsic state  Modern web browsers use this technique to prevent loading same images twice. When browser loads a web page, it traverses through all images on that page. Browser loads all new images from Internet and places them the internal cache. For already loaded images, a flyweight object is created, which has some unique data like position within the page, but everything else is referenced to the cached one.
  • 36. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 36 7.2.7.PROXY PATTERN 1. OVERVIEW  Provide a delegate or placeholder for another object to control access to it.  proxy is a wrapper or agent object that is being called by the client to access the real serving object behind the scenes  For the client, usage of a proxy object is similar to using the real object, because both implement the same interface.  In the proxy extra functionality can be provided rather than real subject like caching or check conditions before call real subject 2. WHEN TO USE  you do not want to instantiate such objects unless and until they are actually requested by the client. Like [protection proxy type]  There are four common situations in which the Proxy pattern is applicable. 1. A virtual proxy: placeholder for "expensive to create" objects. The real object is only created when a client first requests/accesses the object 2. A remote proxy: provides a local representative for an object that resides in a different address space 3. A protective proxy: controls access to a sensitive object. The "surrogate" object checks the caller has the access permissions required prior to forwarding the request. 4. A smart proxy: interposes additional actions when an object is accessed like  Counting the number of references to the real object  Loading a persistent object into memory when it's first referenced  Checking that the real object is locked before it is accessed to ensure that no other object can change it 3. STRUCTURE
  • 37. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 37 Proxy (normal class)  maintains a reference that lets the proxy access the real subject.  provides an interface identical to Subject's so that a proxy can be substituted for the real subject  controls access to the real subject and may be responsible for creating and deleting it  Eg. Proxy Server - ATM Subject (interface - abstract class)  defines the common interface for RealSubject and Proxy so that a Proxy can be used anywhere a RealSubject is expected.  Eg. Server - Bank RealSubject (normal class)  defines the real object that the proxy represents.  Eg. Web Server – DB Server – Concrete Bank 4. CHECK LIST  Identify the leverage or "aspect" that is best implemented as a wrapper or surrogate  Define an interface that will make the proxy and the original component interchangeable.  The wrapper class holds a pointer to the real class and implements the interface.  The pointer may be initialized at construction, or on first use.  Each wrapper method contributes its leverage, and delegates to the wrappee object.
  • 38. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 38 5. CONCEPTUAL EXAMPLE  ATM Machine represent as proxy between customer who need to make transaction and the bank [real subject]  Proxy server in internet represent proxy between client request and destination server  Check represented as proxy between customer and real fund account
  • 39. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 39 4.3. BEHAVIOUR PATTERNS Behavioural design patterns are design patterns that identify common communication patterns between objects and realize these patterns. There are basic 12 pattern for behavioural pattern as follows PATTERN DESCRIPTION Freq. of use Command Encapsulate a command request as an object 4/5 Chain of responsibilities A way of passing a request between a chain of objects 2/5 Interpreter A way to include language elements in a program 1/5 Iterator Sequentially access the elements of a collection 5/5 Mediator Defines simplified communication between classes 2/5 Memento Capture and restore an object's internal state 1/5 Null Object Designed to act as a default value of an object 4/5 Observer A way of notifying change to a number of classes 5/5 State Alter an object's behaviour when its state changes 3/5 Strategy Encapsulates an algorithm inside a class 4/5 Template Method Defer the exact steps of an algorithm to a subclass 3/5 Visitor Defines a new operation to a class without change 1/5
  • 40. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 40 4.3.1. COMMAND PATTERN 1. OVERVIEW  object is used to encapsulate all information needed to perform an action or trigger an event at a later time  This information includes the method name, the object that owns the method and values for the method parameters.  terms associated with command are command, receiver, invoker and client  An object-oriented call-back 2. WHEN TO USE  Need to issue requests to objects without knowing anything about the operation being requested or the receiver of the request.  Command objects are useful for implementing GUI buttons and menu items Macro recording Mobile Code Multi-level undo Networking Progress bars Parallel Processing Thread pools Transactional behaviour Wizards 3. STRUCTURE Command (normal class)  declares an interface for executing an operation  Eg. ICommand ConcreteCommand (normal class)  defines a binding between a Receiver object and an action  implements Execute by invoke the corresponding operation(s) on Receiver  Eg. LightOn, LightOff, AirConditionerOn, ConditionerOff Client (normal class)  creates a ConcreteCommand object and sets its receiver  Eg. User Invoker (normal class)  asks the command to carry out the request  Eg. RemoteController
  • 41. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 41 Receiver (normal class)  how to perform the operations associated with carrying out the request.  Eg. AirConditioner, Light 4. CHECK LIST  Define a Command interface with a method signature like execute ()  Create one or more derived classes that encapsulate some subset of the following: a "receiver" object, the method to invoke, the arguments to pass.  Instantiate a Command object for each deferred execution request.  Pass Command object from the creator (sender) to the invoker (receiver)  The invoker decides when to execute (). 5. CONCEPTUAL EXAMPLE  The customer (client) request order from waiter (invoker) he places the order (command) and the order send to cook (Receiver)  Client click menu item open (invoker) this will call open (command) and this command will execute open file (receiver).
  • 42. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 42 4.3.2. CHAIN OF RESPONSIBILITES PATTERN 1. OVERVIEW  consisting of a source of command objects and a series of processing objects  Each processing object contains logic that defines the types of command objects that it can handle  The rest are passed to the next processing object in the chain  Chain the receiving objects and pass the request along the chain until an object handles it.  An object-oriented linked list with recursive traversal. 2. WHEN TO USE  There is a potentially variable number of "handler" or "processing element" or "node" objects, and a stream of requests that must be handled. Need to efficiently process the requests without hard-wiring handler relationships and precedence, or request-to-handler mappings.  receiving objects together, and then passes any request messages from object to object until it reaches an object capable of handling the message 3. STRUCTURE Handler (abstract class)  defines an interface for handling the requests  (optional) implements the successor link  Eg. Approver ConcreteHandler (normal class)  handles request it is responsible for  can access its successor  if the ConcreteHandler can handle the request, it does so; otherwise it forwards the request to its successor  Eg. (Director, Vice-president, President Client (normal class)  initiates the request to a ConcreteHandler object on the chain  Eg. ChainApp
  • 43. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 43 4. CHECK LIST  The base class maintains a "next" pointer.  Each derived class implements its contribution for handling the request.  If the request needs to be "passed on", then the derived class "calls back" to the base class, which delegates to the "next" pointer.  The client (or some third party) creates and links the chain (which may include a link from the last node to the root node).  The client "launches and leaves" each request with the root of the chain.  Recursive delegation produces the illusion of magic. 5. CONCEPTUAL EXAMPLE  Question flow represent one person handle the request and answer the question, if the first one know he won't ask the next one  The Chain of Responsibility pattern avoids coupling the sender of a request to the receiver by giving more than one object a chance to handle the request. ATM use the Chain of Responsibility in money giving mechanism.
  • 44. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 44 4.3.3. INTERPRETER PATTERN 1. OVERVIEW  The interpreter design pattern provides way to evaluate language grammar or expression. This pattern is used in sql parsing, symbol processing engine etc.  Interpreter involves implementing an expression interface which tells to interpret a particular context. 2. WHEN TO USE  parsing light expressions defined in simple grammars and sometimes in simple rule engines.  Interpreter pattern only in terms of formal grammars but in this area there are better solutions and this is the reason why this pattern is not so frequently used 3. STRUCTURE AbstractExpression (abstract class)  declares an interface for executing an operation  Eg. Expression TerminalExpression  implements Interpret operation related to terminal symbols in grammar.  an instance is required for every terminal symbol in the sentence.  Eg. (ThousandExpression, HundredExpression, TenExpression, OneExpression) NonterminalExpression  defines an interface for handling the requests  (optional) implements the successor link  Eg. Approver Context  contains information that is global to the interpreter  Eg. Context
  • 45. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 45 Client  builds an abstract syntax tree representing a particular sentence in the language that the grammar defines, this will be assembled from instances of the NonterminalExpression and TerminalExpression classes  invokes the Interpret operation  Eg. InterperterApp 4. CHECK LIST  Decide if a "little language" offers a justifiable return on investment.  Define a grammar for the language.  Map each production in the grammar to a class.  Organize the suite of classes into the structure of the Composite pattern.  Define an interpret(Context) method in the Composite hierarchy.  Context object encapsulates the current state of the input and output as the former is parsed and the latter is accumulated. It is manipulated by each grammar class as the "interpreting" process transforms input into output. 5. CONCEPTUAL EXAMPLE  Date interpreter in have multiple date expression and it can receive logic date context format and interpret it to readable format  Google translate is example of interpreter it read the input language and interpreted into other language  Musicians are examples of Interpreters. Tone of a sound and its duration can be represented in musical notation on a staff. This notation provides the language of music. Musicians playing the music from the score are able to reproduce the original tone and duration of each sound represented.
  • 46. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 46 4.3.4. ITERATOR PATTERN 1. OVERVIEW  The iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements  Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.  .NET Framework has special interfaces that support a simple iteration: [System.Collections.IEnumerator] over a non-generic collection and System.Collections. Generic.IEnumerator<T> over a generic collection.  2. WHEN TO USE  Need to "abstract" the traversal of wildly different data structures so that algorithms can be defined that are capable of interfacing with each transparently. 1. STRUCTURE Iterator (abstract class – interface)  defines an interface for accessing and traversing elements.  Has abstract Traversing operation (first, next, isDone, currentitem)  Eg. Iterator ConcreteIterator  implements the Iterator interface.  keeps track of the current position in the traversal of the aggregate.  Eg. FacebookIterator – TwitterIterator both represent iterator Aggregate (abstract class – interface)  defines an interface for creating an Iterator object  Eg. ISocialNetorking ConcreteAggregate  implements the Iterator creation interface to return an instance of the proper ConcreteIterator
  • 47. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 47  Eg. Facebook (include user array), twitter (include user linkedlist) 2. CHECK LIST  Add a create_iterator () method to the "collection" class, and grant the "iterator" class privileged access.  Design an "iterator" class that can encapsulate traversal of the "collection" class.  Clients ask the collection object to create an iterator object.  Clients use the first (), is_done (), next (), andcurrent_item () protocol to access the elements of the collection class. 3. CONCEPTUAL EXAMPLE  In office settings where access to files is made through administrative or secretarial staff, the Iterator pattern is demonstrated with the secretary acting as the Iterator, To the executive, the filing system is confusing and illogical, but the secretary is able to access files quickly and efficiently.  On early television sets, a dial was used to change channels. When channel surfing, the viewer was required to move the dial through each channel position, regardless of whether or not that channel had reception. On modern television sets, a next and previous button are used. When the viewer selects the "next" button, the next tuned channel will be displayed
  • 48. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 48 4.3.5. MEDIATOR PATTERN 1. OVERVIEW  The mediator is the communication centre of the objects.  When an object needs to communicate to another object, it doesn’t call the other object directly. Instead it calls the mediator object which is to route the communication to the destination object.  Ensures that the components are loosely coupled, such that they don't call each other explicitly; rather they always use a separate Mediator implementation to do those jobs 2. WHEN TO USE  reduce communication complexity between multiple objects or classes  design reusable components, organize dependency between reusable pieces and avoid spaghetti code  reduce coupling between objects 3. STRUCTURE Mediator (abstract class - interface)  Defines an interface for communicating with Colleague objects  Eg. IChatRoom Concrete Mediator  implements cooperative behaviour by coordinating Colleague objects  knows and maintains its colleagues  Eg. Chatroom Colleague classes  each Colleague class knows its Mediator object  each colleague communicates with its mediator whenever it would have otherwise communicated with another colleague  Eg. Participant
  • 49. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 49 4. CHECK LIST  Identify a collection of interacting objects that would benefit from mutual decoupling.  Encapsulate those interactions in the abstraction of a new class.  Create an instance of that new class and rework all "peer" objects to interact with the Mediator only.  Balance the principle of decoupling with the principle of distributing responsibility evenly.  Be careful not to create a "controller" object. 5. CONCEPTUAL EXAMPLE  Chat room represent mediator between people need to contact to each other  Facebook group represent mediator between users join it if anything updated it will route to all registered users  In Air Traffic Control (ATC) mediator, the pilots of the planes approaching or departing the terminal area communicate with the tower rather than explicitly communicating with one another  The constraints on who can take off or land are enforced by the tower.  It is important to note that the tower does not control the whole flight. It exists only to enforce constraints in the terminal area.
  • 50. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 50 4.3.6. MOMENTO PATTERN 1. OVERVIEW  The Memento captures and externalizes an object's internal state so that the object can later be restored to that state 2. WHEN TO USE  Need to restore an object back to its previous state (e.g. "undo" or "rollback" operations). 3. STRUCTURE Memento (abstract class - interface)  Defines an interface for communicating with Colleague objects  the lock box that is written and read by the Originator, and derived by the Caretaker  Eg. Memento Originator  creates a memento containing a snapshot of its current internal state.  uses the memento to restore its internal state  the object that knows how to save itself.  Eg. Sales Prospect Caretaker  is responsible for the memento's safekeeping  never operates on or examines the contents of a memento.  the object that knows why and when the Originator needs to save and restore itself.  Eg. Caretaker
  • 51. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 51 4. CHECK LIST  Identify the roles of “caretaker” and “originator”.  Create a Memento class and declare the originator a friend.  Caretaker knows when to "check point" the originator.  Originator creates a Memento and copies its state to that Memento.  Caretaker holds on to (but cannot peek into) the Memento.  Caretaker knows when to "roll back" the originator.  Originator reinstates itself using the saved state in the Memento. 5. CONCEPTUAL EXAMPLE  Mechanics repairing drum brakes on their cars. The drums are removed from both sides, exposing both the right and left brakes.  Only one side is disassembled and the other serves as a Memento of how the brake parts fit together.  Only after the job has been completed on one side is the other side disassembled.  When the second side is disassembled, the first side acts as the Memento.
  • 52. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 52 4.3.7. NULL OBJECT PATTERN 1. OVERVIEW  Null Object is an object with no referenced value or with defined neutral ("null") behaviour.  The Null Object design pattern describes the uses of such objects and their behaviour 2. WHEN TO USE references may be null. These references need to be checked to ensure they are not null before invoking any methods, because methods typically cannot be invoked on null references 3. STRUCTURE Client  declares an interface for executing an operation AbstractObject  declares the interface for Client's collaborator  implements default behaviour for the interface common to all classes, as appropriate RealObject  defines a concrete subclass of AbstractObject whose instances provide useful behaviour that Client expects NullObject  provides an interface identical to Abstract Object's so that a null object can be substituted for a real object  implements its interface to do nothing What exactly it means to do nothing depends on what sort of behaviour Client is expecting  when there is more than one way to do nothing, more than one NullObject class may be required
  • 53. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 53 4. CHECK LIST  Create abstract class that defines the interface for all objects of this type  Create Null Object is implemented as a subclass of this abstract class 5. CONCEPTUAL EXAMPLE  N/A
  • 54. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 54 4.3.8. OBSERVER PATTERN 1. OVERVIEW  Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.  Observer pattern is also a key part in the familiar model–view–controller (MVC) architectural pattern 2. WHEN TO USE  the change of a state in one object must be reflected in another object without keeping the objects tight coupled.  the framework we are writing needs to be enhanced in future with new observers with minimal changes. 3. STRUCTURE Subject  Any number of Observer objects may observe a subject  provides an interface for attaching and detaching Observer objects.  Eg. Stock Concrete Subject  stores state of interest to Concrete Observer  sends a notification to its observers when its state changes  Eg. IBM Observer  Defines an updating interface for objects that should be notified of changes in a subject.  Eg. IInvestor Concrete Observer  maintains a reference to a Concrete Subject object  stores state that should stay consistent with the subject's
  • 55. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 55  implements the Observer updating interface to keep its state consistent with the subject's  Eg. Investor 4. CHECK LIST  Differentiate between the core (or independent) functionality and the optional (or dependent) functionality.  Model the independent functionality with a "subject" abstraction.  Model the dependent functionality with an "observer" hierarchy.  The Subject is coupled only to the Observer base class.  The client configures the number and type of Observers.  Observers register themselves with the Subject.  The Subject broadcasts events to all registered Observers.  The Subject may "push" information at the Observers, or, the Observers may "pull" the information they need from the Subject 5. CONCEPTUAL EXAMPLE  Example 1: News Agency  A news agency gathers news and publish them to different subscribers.  We need to create a framework for and agency to be able to inform immediately, when event occurs, its subscribers about the event.  The subscribers can receive the news in different ways: Emails, SMS  Example 2: Some auctions  Each bidder possesses a numbered paddle that is used to indicate a bid.  The auctioneer starts the bidding, and "observes" when a paddle is raised to accept the bid.  The acceptance of the bid changes the bid price which is broadcast to all of the bidders in the form of a new bid.
  • 56. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 56 4.3.9. STATE PATTERN 1. OVERVIEW  Allow an object to alter its behaviour when its internal state changes  known as the objects for states pattern  The object will appear to change its class.  An object-oriented state machine 2. WHEN TO USE  encapsulate varying behaviour for the same object based on its internal state.  a cleaner way for object to change its behaviour at runtime without resorting to large solid conditional statements and thus improve maintainability 3. STRUCTURE Context  defines the interface of interest to clients  maintains instance of a ConcreteState subclass to defines the current state.  Eg. Account state (interface – abstract class)  defines an interface for encapsulating the behavior associated with a particular state of the Context.  Eg. State ConcreteState  each subclass implements a behavior associated with a state of Context  Eg. (RedState, SilverState, GoldState)
  • 57. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 57 4. CHECK LIST  Identify an existing class, or new class, that will serve as the "state machine" from the client's perspective. That class is the "wrapper" class.  Create a State base class that replicates the methods of the state machine interface. Each method takes one additional parameter: an instance of the wrapper class. The State base class specifies any useful "default" behavior.  Create a State derived class for each domain state. These derived classes only override the methods they need to override.  The wrapper class maintains a "current" State object.  All client requests to the wrapper class are simply delegated to the current State object, and the wrapper object's this pointer is passed.  The State methods change the "current" state in the wrapper object as appropriate. 5. CONCEPTUAL EXAMPLE  ATM has states like [no debit card] state and you can only insert card and [has debit card] state you can do other multiple operations  SLDC (software development lifecycle) are states of any application from requirement to maintenance  TV Remote control has states on, off and each state has set of operations  Vending Machine has multiple status like [money not inserted, product not selected] and [money inserted and product selected]
  • 58. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 58 4.3.10. STRATEGY PATTERN 1. OVERVIEW  Define a family of algorithms, encapsulate each one, and make them interchangeable  Strategy lets the algorithm vary independently from the clients that use it.  Capture the abstraction in an interface, bury implementation details in derived classes. 2. WHEN TO USE  Help to activate [open-closed principle] should be open for extension, but closed for modification  If your system needs to dynamically select one of several algorithms.  If your system in which there are many classes, then if you need dynamically allows to choose a behavior use the strategy pattern 3. STRUCTURE Context  is configured with a ConcreteStrategy object  maintains a reference to a Strategy object  may define an interface that lets Strategy access its data.  Eg. SortedList Strategy (interface – abstract class)  declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy  Eg. Sort Strategy ConcreteStrategy  implements the algorithm using the Strategy interface  Eg. (QuickSort, ShellSort, MergeSort)
  • 59. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 59 4. CHECK LIST  Identify an algorithm (i.e. a behavior) that the client would prefer to access through a "flex point".  Specify the signature for that algorithm in an interface.  Bury the alternative implementation details in derived classes.  Clients of the algorithm couple themselves to the interface. 5. CONCEPTUAL EXAMPLE  Compress files may be done by two strategy compress using zip or using rar then send result to client  When customer purchase something from mall, he can choose to pay using different strategies like credit cards, debit cards or cache  When client need to go to airport he can choose from different transport strategies like taxi, bus, metro, etc.
  • 60. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 60 4.3.11. TEMPLATE METHOD PATTERN 1. OVERVIEW  defines the program skeleton of an algorithm in a method  let one redefine certain steps of an algorithm without changing the algorithm's structure  Base class declares algorithm 'placeholders', and derived classes implement the placeholders.  Base class is created that provides the basic steps of an algorithm design. These steps are implemented using abstract methods. Later on, subclasses change the abstract methods to implement real actions. 2. WHEN TO USE  used in frameworks, where each implements the invariant parts of a domain's architecture, leaving "placeholders" for customisation options  Let subclasses implement (through method overriding) behavior that can vary  Avoid duplication in the code  Control at what point(s) sub classing is allowed 3. STRUCTURE AbstractClass (interface – abstract class)  defines abstract primitive operations that concrete subclasses define to implement steps of an algorithm  implements a template method defining the skeleton of an algorithm.  The template method calls primitive operations as well as operations defined in AbstractClass or those of other objects.  Eg. DataObject ConcreteClass  implements the primitive operations to carry out subclass-specific steps of the algorithm  Eg. CustomerDataObject
  • 61. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 61 4. CHECK LIST  Examine the algorithm, and decide which steps are standard and which steps are peculiar to each of the current classes.  Define a new abstract base class to host the "don't call us, we'll call you" framework.  Move the shell of the algorithm (now called the "template method") and the definition of all standard steps to the new base class.  Define a placeholder or "hook" method in the base class for each step that requires many different implementations. This method can host a default implementation  Invoke the hook method(s) from the template method.  Each of the existing classes declares an "is-a" relationship to the new abstract base class.  Remove from the existing classes all the implementation details that have been moved to the base class.  The only details that will remain in the existing classes will be the implementation details peculiar to each derived class. 5. CONCEPTUAL EXAMPLE  Home builders use the Template Method when developing a new subdivision  A typical subdivision consists of a limited number of floor plans with different variations available for each  Within a floor plan, the foundation, framing, plumbing, and wiring will be identical for each house  Other example is daily routine of a worker.
  • 62. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 62 4.3.12. VISITOR PATTERN 1. OVERVIEW  visitor design pattern is a way of separating an algorithm from an object structure on which it operates.  A practical result of this separation is the ability to add new operations to existing object structures without modifying those structures.  one way to follow the open/closed principle. 2. WHEN TO USE  Similar operations have to be performed on objects of different types grouped in a structure (a collection or a more complex structure).  There are many distinct and unrelated operations needed to be performed. Visitor pattern allows us to create a separate visitor concrete class for each operation type and to separate operation implementation from the objects structure.  The object structure is not likely to be changed but is very probable to have new operations which have to be added.  Since the pattern separates the visitor (representing operations, algorithms, behaviours) from the object structure it's very easy to add new visitors as long as the structure remains unchanged. 3. STRUCTURE Visitor (Visitor)  declares a Visit operation for each class of concreteElement in object structure  The operation's name and signature identifies the class that sends the Visit request to the visitor That lets the visitor determine the concrete class of the element being visited.  Then the visitor can access the elements directly using its particular interface  Eg. Visitor
  • 63. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 63 ConcreteVisitor  implements each operation declared by Visitor.  Each operation implements a fragment of the algorithm defined for the corresponding class or object in the structure.  ConcreteVisitor provides the context for the algorithm and stores its local state.  This state often accumulates results during the traversal of the structure.  Eg. (IncomeVisitor, VacationVisitor) Element  defines an Accept operation that takes a visitor as an argument.  Eg. Element ConcreteElement  implements an Accept operation that takes a visitor as an argument  Eg. Employee ObjectStructure  can enumerate its elements  may provide a high-level interface to allow the visitor to visit its elements  may either be a Composite (pattern) or a collection such as a list or a set  Eg. Employees 4. CHECK LIST  Confirm that the current hierarchy (known as the Element hierarchy) will be fairly stable and that the public interface of these classes is sufficient for the access the Visitor classes will require. If these conditions are not met, then the Visitor pattern is not a good match.  Create a Visitor base class with a visit(ElementXxx)method for each Element derived type.  Add an accept(Visitor) method to the Element hierarchy. The implementation in each Element derived class is always the same – accept (Visitor v) {v. visit (this);}. Because of cyclic dependencies, the declaration of the Element and Visitor classes will need to be interleaved.  The Element hierarchy is coupled only to the Visitor base class, but the Visitor hierarchy is coupled to each Element derived class. If the stability of the Element hierarchy is low, and the stability of the Visitor hierarchy is high; consider swapping the 'roles' of the two hierarchies.  Create a Visitor derived class for each "operation" to be performed on Element objects. visit () implementations will rely on the Element's public interface.  The client creates Visitor objects and passes each to Element objects by calling accept ().
  • 64. .NET – DESIGN PATTERNS ‫السعودي‬ ‫البريد‬ .NET – DESIGN PATTERN Page | 64 5. CONCEPTUAL EXAMPLE  the operation of a taxi company. When a person calls a taxi company (accepting a visitor), the company dispatches a cab to the customer. Upon entering the taxi, the customer, or Visitor, is no longer in control of his or her own transportation, the taxi (driver) is.