structural patterns 06-sep-2012 presenters sanjeeb kumar nanda & vidya prabha kanakarajan

62
STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

Upload: ami-casey

Post on 01-Jan-2016

214 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

STRUCTURAL PATTERNS

06-Sep-2012

PresentersSanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

Page 2: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

2

What is a pattern?

• Pattern is a recurring solution to a standard problem

• Each Pattern describes a problem which occurs over and over again in our environment and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice

• Not code reuse

‒ Instead, solution/strategy reuse

‒ Sometimes, interface reuse

Page 3: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

3

How patterns arise

ProblemProblem

Context

SolutionSolution

Benefits

Related Patterns

Consequences

Forces

Page 4: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

4

Description of Design Pattern

• Pattern name and classification

• Intent

• Motivation

• Applicability

• Structure (diagram)

• Sample Code

• Known Uses

Page 5: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

5

Four essential elements of pattern

• Pattern Name

‒ Naming a pattern immediately increases our design vocabulary. It let's design at a higher level of abstraction.

• Problem

‒ It explains the problem and its context. It might describe specific design problems such as how to represent algorithms as objects.

• Solution

‒ The solution describes the elements that make up the design, their relationships, responsibilities, and collaborations.

• Consequences

‒ The consequences are the results and trade-offs of applying the pattern

Page 6: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

6

Pattern Categories

Categories are based on granularity and level of abstraction

• Creational

‒ It helps in the process of object creation

‒ Factory Method, Abstract Factory, Singleton., etc.

• Structural

‒ Defines composition of objects and classes

‒ Uses inheritance to compose classes, while the Structural object patterns describe ways to assemble objects.

‒ Adapter, Façade, Proxy., etc.

• Behavioral

‒ Characterizes the way in which classes or objects interact

‒ The Behavioral class patterns use inheritance to describe algorithms and flow of control, whereas the Behavioral object patterns describe how a group of objects

co-operate to perform a task that no single object can carry out alone .

‒ Observer, Iterator, Visitor, etc.

Page 7: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

7

Design Patterns Catalog

Purpose

Creational Structural Behavioral

Scope Class Factory Method Adapter InterpreterTemplate Method

Object Abstract Factory Builder Prototype Singleton

Adapter BridgeComposite Decorator FacadeFlyweight Proxy

Chain of Responsibility Command Iterator Mediator Memento Observer State Strategy Visitor

Page 8: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

8

Page 9: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

9

Structural Design Patterns

Pattern Intent

Adapter Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

Bridge Decouple an abstraction from its implementation so that the two can vary independently.

Composite Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

Decorator Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

Façade 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

Proxy Use sharing to support large numbers of fine-grained objects efficiently.

Flyweight Provide a surrogate or placeholder for another object to control access to it.

Page 10: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

10

Adapter Pattern

• Intent

‒ Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

• Also Known As

‒ Wrapper

• Frequency of use: Medium - high

• Applicability

Use the Adapter pattern when

‒ you want to use an existing class, and its interface does not match the one you need.

‒ you want to create a reusable class that cooperates with unrelated or unforeseen classes, that is, classes that don't necessarily have compatible interfaces.

‒ (object adapter only) you need to use several existing subclasses, but it's impractical to adapt their interface by subclassing every one. An object adapter can adapt the interface of its parent class.

Page 11: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

11

Adapter Pattern

Page 12: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

12

Types of Adapter Pattern

• Class Adapter

‒ Class adapter uses inheritance instead of composition. It means that instead of delegating the calls to the Adaptee, it subclasses it

• Object Adapter

‒ It uses composition, the Adaptee delegates the calls to Adaptee (opposed to class adapters which extends the Adaptee). Extensible to subclasses of the adapter.

• Two-way Adapter

‒ The Two-Ways Adapters are adapters that implements both interfaces of Target and Adaptee. The adapted object can be used as Target in new systems dealing with Target classes or as Adaptee in other systems dealing with Adaptee classes. Enables different clients to view an object differently. If adapter has to extend the Target class it can not extent another class like Adaptee, so the Adaptee should be an interface and all the calls should be delegated from the adapter to the Adaptee object.

• Pluggable Adapter

‒ Presence of adapter is transparent. It can be put in and taken out. Several Adapters can be active. The pluggable adapter pattern takes polymorphism. Usually the adapter decides which class it is adapting based on differing constructors or setParameter methods

Page 13: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

13

Adapter Pattern (Class) – Structure

• A class adapter uses multiple inheritance to adapt one interface to another

• Implements a specific Adaptee class, so you cann’t adopt the adaptee’s subclasses

• Can override Adaptee’s behaviour

Page 14: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

14

Adapter Pattern (Object) - Structure

• An object adapter relies on object composition and uses delegation

• Can implement / extend more than one adaptee class

• May complicate overriding adaptee behaviour but can extend the Adaptee’s behaviour

Page 15: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

15

Adapter Pattern - Participants

• Target (Connector)

‒ defines the domain-specific interface that Client uses.

• Client (Main.cs)

‒ collaborates with objects conforming to the Target interface.

• Adaptee (DatabaseHelper)

‒ defines an existing interface that needs adapting.

• Adapter (DatabaseAdapter)

‒ adapts the interface of Adaptee to the Target interface.

Page 16: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

16

Adapter Pattern – Real Time Examples

• AC Adaptors

• Car chargers for mobile Phones

• DataAdapters in .Net

• COM InterOp in .Net

• Character Encoding & Decoding in .Net

• StreamAdapter in .Net

Page 17: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

17

Adapter Pattern – Real Time Examples

DataAdapter:• DataAdapter class in .NET Framework represents a set of data commands and a database

connection that are used to fill the DataSet and update the data source.

• The DataAdapter serves as a bridge between a DataSet and a data source for retrieving and saving data. The DataAdapter provides this bridge by mapping Fill, which changes the data in the DataSet to match the data in the data source, and update that changes the data in the data source to match the data in the DataSet.

• For example:

using (SqlConnection connection = new SqlConnection(connectionString)) // connectionString retrieves the connection string from a configuration file

{

SqlDataAdapter adapter = new SqlDataAdapter(“select * from employees”, connection);

DataSet ds = new DataSet();

Adapter.Fill(ds, “Employees”);

}

Adaptee - Data Source (SQL Server)

Target - DataSet

Adapter - SqlDataAdapter

Target Method - Fill (Dataset instance)

Page 18: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

18

Adapter Pattern – Real Time Examples

Character Encoding and Decoding:• System.Text namespace contains the classes such as Encoding, ASCIIEncoding, UnicodeEncoding

and UTF8Encoding to encode and decode characters that act as adapter classes.

• For example:

string MyString = “Encoding String”;

ASCIIEncoding AE = new ASCIIEncoding();

Byte[] ByteArray = AE.GetBytes(MyString);

for (int x=0; x <= ByteArray.Length – 1; x++)

{

Console.Write(“{0} “,ByteArray[x]);

}

Adaptee - String

Target - Byte

Adapter – ASCIIEncoding

Client - the class that wants to convert Unicode string into Array of Bytes

Target Method - GetBytes(string)

Page 19: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

19

Adapter Pattern – Real Time Examples

Interoperation with COM:

• A .NET client accesses a COM server by means of RCW as shown in figure below.

• The RCW wraps the COM object and mediates between it and the common language runtime environment, making the COM object appear to .NET clients just as if it were a native .NET object and making the .NET client appear to the COM object just as if it were a standard COM client. A COM client accesses a .NET object through CCW. The CCW wraps up the .NET object and mediates between it and the common language runtime environment, making the .NET object appear to COM clients just as if were a native COM object

Page 20: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

20

Adapter Pattern – Real Time Examples

• Stream Adapters:

A Stream deals only in bytes; to read or write data types such as strings, integers or XML elements, we must plug in an adapter.

Page 21: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

21

Adapter Pattern – Related Patterns

• Bridge has a structure similar to an object adapter, but Bridge has a different intent: It is meant to separate an interface from its implementation so that they can be varied easily and independently. An adapter is meant to change the interface of an existing object.

• Façade is an object that provides a simplified interface to a larger body of code such as class library. Wrap a poorly-designed collection of APIs with a single well-defined API. It hides the complexity of a subsystem or simplifies its interface. Facade routinely wraps multiple objects and Adapter wraps a single object.

• Proxy defines a representative or surrogate for another object and does not change its interface.

Page 22: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

22

Decorator Pattern

• Intent

‒ Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

• Also Known As

‒ Wrapper

• Frequency of use : Medium  

• Applicability

‒ To add /remove responsibilities to individual objects dynamically and transparently, i.e. without affecting other objects

‒ When extension by sub-classing is impractical. Sometimes a large number of independent extensions are possible and would produce an explosion of subclasses to support every combination. Or a class definition may be hidden or otherwise unavailable for sub-classing

Page 23: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

23

Decorator - Structure

Page 24: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

24

Decorator - Participants

• Participants

‒ Component

• Defines the interface for objects that can have responsibilities added to them dynamically.

‒ ConcreteComponent (SimpleStreamWriter)

• Defines an object to which additional responsibilities can be attached..

‒ Decorator (StreamWriterDecorator)

• Maintains a reference to a Component object and defines an interface that conforms to Component's interface.

‒ ConcreteDecorator (LowerCaseDecorator, TitleCaseDecorator)

• Adds responsibilities to the component.

• Decorator forwards requests to its Component object. It may optionally perform additional operations before and after forwarding the request.

Page 25: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

25

Decorator Example

Page 26: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

26

Decorator Example

Page 27: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

27

Decorator Pattern – Real Time Examples

• Graphics

• In today’s world of mobile devices, web browsers and other mobile applications thrive on Decorator pattern. They can create display objects suitable for smaller screens that include scroll bars and exclude banners that would be the standard on desktop display browsers for example.

• Streams

• System.IO.Stream

• System.IO.BufferedStream

• System.IO.Compression.DeflateStream

• System.IO.Compression.GZipStream

• System.Net.Security.AuthenticatedStream

• System.Security.Crypotography.CryptoStream

The subclasses decorate Stream because they inherit from it and also contain an instance of a Stream that is set up when an object is constructed.

• Decorators in GUI

• System.Windows.Controls provide a base class for elements that apply effects onto or around a single client element such as Border or View Box.

Page 28: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

28

Decorator Pattern – Real Time Examples

Decorator Streams:

Page 29: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

29

Decorator Pattern

• Advantages

‒ fewer classes than with static inheritance

‒ dynamic addition/removal of decorators

‒ keeps root classes simple

• Disadvantages

‒ proliferation of run-time instances

‒ abstract Decorator must provide common interface

• Tradeoffs:

‒ useful when components are lightweight

‒ otherwise use Strategy

Page 30: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

30

Decorator Pattern – Related Patterns

• Related Patterns

‒ Adapter

• A decorator is different from an adapter in that a decorator only changes an object's responsibilities, not its interface; an adapter will give an object a completely new interface.

‒ Composite

• A decorator can be viewed as a degenerate composite with only one component. However, a decorator adds additional responsibilities. It isn't intended for object aggregation.

‒ Strategy

• A decorator lets you change the skin of an object; a strategy lets you change the guts. These are two alternative ways of changing an object.

Page 31: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

31

Composite Pattern

Intent

‒ Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

Frequency of use: Medium – high

Applicability

Use the Composite pattern when

‒ you want to represent part-whole hierarchies of objects.

‒ you want clients to be able to ignore the difference between compositions of objects and individual objects. Clients will treat all objects in the composite structure uniformly.

Page 32: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

32

Composite Pattern - Structure

Page 33: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

33

Composite Pattern - Participants

• Component (IEmployee, IEnumerator)

‒ declares the interface for objects in the composition.

‒ implements default behavior for the interface common to all classes, as appropriate.

‒ declares an interface for accessing and managing its child components.

‒ (optional) defines an interface for accessing a component's parent in the recursive structure, and implements it if that's appropriate.

• Leaf (Employee, Contractor)

‒ represents leaf objects in the composition. A leaf has no children.

‒ defines behavior for primitive objects in the composition.

• Composite (Employee)

‒ defines behavior for components having children.

‒ stores child components.

‒ implements child-related operations in the Component interface.

• Client (Main.cs)

‒ manipulates objects in the composition through the Component interface.

Page 34: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

34

Composite Pattern

• Makes use of the following features:

‒ Generics

‒ Properties

‒ Struct

‒ Indexers

‒ Implicit Typing

‒ Initializers

‒ Anonymous Types

Page 35: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

35

Composite Pattern - Real Time Examples

• TreeNodeCollection class & ToolStrip class

• CompositeControl class

• Files and Folders

• Organizational Tree

• Arithmethic Expresssion

• Generic containers

Page 36: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

36

Composite Pattern – Related Patterns

• Decorator is often used with Composite. When decorators and composites are used together, they will usually have a common parent class. So decorators will have to support the Component interface with operations like Add, Remove, and GetChild.

• Flyweight lets you share components, but they can no longer refer to their parents.

• Iterator can be used to traverse composites.

• Visitor localizes operations and behavior that would otherwise be distributed across Composite and Leaf classes.

Page 37: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

37

Façade Pattern

Intent

‒ Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.

Frequency of use: High

Applicability

Use the Facade pattern when

‒ you want to provide a simple interface to a complex subsystem.

‒ there are many dependencies between clients and the implementation classes of an abstraction. Introduce a facade to decouple the subsystem from clients and other subsystems, thereby promoting subsystem independence and portability.

‒ you want to layer your subsystems. Use a facade to define an entry point to each subsystem level. If subsystems are dependent, then you can simplify the dependencies between them by making them communicate with each other solely through their facades.

Page 38: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

38

Façade Pattern - Structure

FacadeClient

Subsystem

Page 39: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

39

Façade Pattern - Participants

• Facade (Compiler)

‒ knows which subsystem classes are responsible for a request.

‒ delegates client requests to appropriate subsystem objects.

• Subsystem classes (Scanner, Parser, ProgramNode, etc.)

‒ implement subsystem functionality.

‒ handle work assigned by the Facade object.

‒ have no knowledge of the facade; that is, they keep no references to it.

Page 40: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

40

Façade Pattern – Real Time Examples

• Wedding Planners/ Event Management

• DirectX / OpenGL

• Online Bill Payment

• Macros in MSOffice

• Front desk for any company.

• Customer care Help desk.

• Amazon.com 1-Click system

Page 41: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

41

Façade Pattern – Related Patterns

• Abstract Factory can be used with Facade to provide an interface for creating subsystem objects in a subsystem-independent way. Abstract Factory can also be used as an alternative to Facade to hide platform-specific classes.

• Mediator is similar to Facade in that it abstracts functionality of existing classes. However, Mediator's purpose is to abstract arbitrary communication between colleague objects, often centralizing functionality that doesn't belong in any one of them.

• Usually only one Facade object is required. Thus Facade objects are often Singletons.

Page 42: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

42

Bridge Pattern

Intent

‒ Decouple an abstraction from its implementation so that the two can vary independently.

Also Known As

‒ Handle/Body

Frequency of use: Medium

Applicability

Use the Bridge pattern when

‒ you want to avoid a permanent binding between an abstraction and its implementation. This might be the case, for example, when the implementation must be selected or switched at run-time.

‒ both the abstractions and their implementations should be extensible by sub classing. In this case, the Bridge pattern lets you combine the different abstractions and implementations and extend them independently.

‒ changes in the implementation of an abstraction should have no impact on clients; that is, their code should not have to be recompiled.

Page 43: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

43

Bridge Pattern - Structure

Page 44: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

44

Bridge Pattern - Participants

• Abstraction (Window) ‒ defines the abstraction's interface.

‒ maintains a reference to an object of type Implementor.

• RefinedAbstraction (IconWindow) ‒ Extends the interface defined by Abstraction.

• Implementor (WindowImp) ‒ defines the interface for implementation classes. This interface

doesn't have to correspond exactly to Abstraction's interface; in fact the two interfaces can be quite different. Typically the Implementor interface provides only primitive operations, and Abstraction defines higher-level operations based on these primitives.

• ConcreteImplementor (XWindowImp, PMWindowImp) ‒ implements the Implementor interface and defines its concrete

implementation.

Page 45: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

45

Bridge Pattern – Real Time Examples

• A household switch controlling lights, ceiling fans, etc. is an example of the Bridge. 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

• Windows forms as Bridges 

The .NET visual control is an example of a Bridge pattern implementation. A control is a reusable software component that can be manipulated visually in a builder tool.

All of the C# controls support a query interface that enables builder programs to enumerate their properties and display them for easy modification. Visual Studio.NET displays a builder panel that is used to modify the properties of all the controls that are displayed in the form. All windows form controls have the same interface used by the Builder program and we can substitute any control for any other and still manipulate its properties using the same convenient interface. The actual program which we construct uses these classes in a conventional way, each having its own rather different methods, but from the builder’s point of view, they all appear to be the same

• Database Drivers as Bridges

In .NET, we can use the OledbDataReader class to work with almost any database, including SQL Server

Page 46: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

46

Bridge Pattern – Related Patterns

• An Abstract Factory can create and configure a particular Bridge.

• The Adapter pattern is geared toward making unrelated classes work together. It is usually applied to systems after they're designed. Bridge, on the other hand, is used up-front in a design to let abstractions and implementations vary independently.

Page 47: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

47

Flyweight Pattern

Intent

‒ Use sharing to support large numbers of fine-grained objects efficiently.

Frequency of use: Low

Applicability

The Flyweight pattern's effectiveness depends heavily on how and where it's used. Apply the Flyweight pattern when all of the following are true:

‒ An application uses a large number of objects.

‒ Storage costs are high because of the sheer quantity of objects.

‒ Most object state can be made extrinsic.

‒ Many groups of objects may be replaced by relatively few shared objects once extrinsic state is removed.

‒ The application doesn't depend on object identity. Since flyweight objects may be shared, identity tests will return true for conceptually distinct objects.

Page 48: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

48

Flyweight - Structure

Page 49: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

49

Flyweight - Participants

• Flyweight

‒ declares an interface through which flyweights can receive and act on extrinsic state.

• ConcreteFlyweight (Character)

‒ implements the Flyweight interface and adds storage for intrinsic state, if any. A ConcreteFlyweight object must be sharable. Any state it stores must be intrinsic; that is, it must be independent of the ConcreteFlyweight object's context.

• UnsharedConcreteFlyweight (Row, Column)

‒ not all Flyweight subclasses need to be shared. The Flyweight interface enables sharing; it doesn't enforce it. It's common for UnsharedConcreteFlyweight objects to have ConcreteFlyweight objects as children at some level in the flyweight object structure (as the Row and Column classes have).

• FlyweightFactory

‒ creates and manages flyweight objects.

‒ ensures that flyweights are shared properly. When a client requests a flyweight, the FlyweightFactory object supplies an existing instance or creates one, if none exists.

• Client

‒ maintains a reference to flyweight(s).

‒ computes or stores the extrinsic state of flyweight(s).

Page 50: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

50

Flyweight – Real Time Examples

• Thumbnail representation of images in windows explorer.

• Order processing system where the items are relatively similar and differ only in certain characteristics

• Representation of files and folders in windows explorer

• Individual cells in spreadsheet program

Page 51: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

51

Flyweight – Related Patterns

• The Flyweight pattern is often combined with the Composite pattern to implement a logically hierarchical structure in terms of a directed-acyclic graph with shared leaf nodes.

• It's often best to implement State and Strategy objects as flyweights.

Page 52: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

52

Proxy Pattern

Intent

‒ Provide a surrogate or placeholder for another object to control access to it.

Also Known As

‒ Surrogate

Frequency of use: Medium - high

Page 53: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

53

Proxy Pattern - Applicability

Proxy is applicable whenever there is a need for a more versatile or sophisticated reference to an object than a simple pointer. Here are several common situations in which the Proxy pattern is applicable:

‒ A remote proxy provides a local representative for an object in a different address space.

‒ A virtual proxy creates expensive objects on demand.

‒ A protection proxy controls access to the original object. Protection proxies are useful when objects should have different access rights.

Page 54: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

54

Proxy Pattern - Structure

Page 55: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

55

Proxy Pattern - Participants

• Maintains a reference that lets the proxy access the real subject. Proxy may refer to a Subject if the RealSubject and Subject interfaces are the same.

• Provides an interface identical to Subject's so that a proxy can by substituted for the real subject.

• Controls access to the real subject and may be responsible for creating and deleting it.

• Other responsibilities depend on the kind of proxy:

‒ remote proxies are responsible for encoding a request and its arguments and for sending the encoded request to the real subject in a different address space.

‒ virtual proxies may cache additional information about the real subject so that they can postpone accessing it. For example, the ImageProxy from the Motivation caches the real image's extent.

‒ protection proxies check that the caller has the access permissions required to perform a request.

• Subject (Graphic)

‒ defines the common interface for RealSubject and Proxy so that a Proxy can be used anywhere a RealSubject is expected.

• RealSubject (Image)

‒ defines the real object that the proxy represents.

Page 56: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

56

Proxy – Real Time Examples

• Data Proxy:

The .NET OleDbDataReader, OdbcDataReader and OracleDataReader classes provide “data reader” objects that let us read data from a database table. These classes are sealed so we cannot subclass them. If we want to control the behavior of a data reader object, Proxy provides an answer.OldDbDataReader, OdbcDataReader and OracleDataReader implement an IdataReader interface. We can create a new class that implements this interface. An instance of our class can selectively forward calls to an underlying instance of OleDbDataReader,

OdbcDataReader and OracleDataReader.

• Remote Proxies:

ASP.NET Web Services. ASP.NET is that it lets client programs interact with a local object that is a proxy for a remote object. The interface for the proxy will match the interface of the remote object so client developers hardly need to be aware of the remote calls that take place.

Page 57: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

57

Proxy Pattern – Related Patterns

• Adapter:

‒ An adapter provides a different interface to the object it adapts. In contrast, a proxy provides the same interface as its subject. However, a proxy used for access protection might refuse to perform an operation that the subject will perform, so its interface may be effectively a subset of the subject's.

• Decorator:

‒ Although decorators can have similar implementations as proxies, decorators have a different purpose. A decorator adds one or more responsibilities to an object, whereas a proxy controls access to an object.

Page 58: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

58

Design Principles

• Encapsulate what varies

• Favor composition over inheritance

• Program to an interface not to an implementation

• Strive for loosely coupled designs between objects that interact

• Classes should be open for extension but closed for modification

• Depend on abstractions. Do not depend on concrete classes.

• Only talk to your friends

• Don’t call us, we will call you

• A class should have only one reason to change

Page 59: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

59

Concluding remarks

• Design Patterns (GoF) provide a foundation for further understanding of:

‒ Object-Oriented design

‒ Software Architecture

• Understanding patterns can take some time

‒ Re-reading them over time helps

‒ As does applying them in your own designs

• Online URL

‒ www.dofactory.com

Page 60: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

60

Mindset on Patterns

Page 61: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

61

Design Pattern Questions

Page 62: STRUCTURAL PATTERNS 06-Sep-2012 Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan

62

Sanjeeb Kumar Nanda