620 likes | 760 Views
STRUCTURAL PATTERNS. Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan. 06 -Sep-2012. What is a pattern?. Pattern is a recurring solution to a standard problem
E N D
STRUCTURAL PATTERNS Presenters Sanjeeb Kumar Nanda & Vidya Prabha Kanakarajan 06-Sep-2012
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
How patterns arise Problem Context Forces Solution Benefits Consequences Related Patterns
Description of Design Pattern • Pattern name and classification • Intent • Motivation • Applicability • Structure (diagram) • Sample Code • Known Uses
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
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.
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.
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
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’sbehaviour
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 adapteebehaviour but can extend the Adaptee’sbehaviour
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.
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
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); DataSetds = new DataSet(); Adapter.Fill(ds, “Employees”); } Adaptee - Data Source (SQL Server) Target -DataSet Adapter - SqlDataAdapter Target Method - Fill (Dataset instance)
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)
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
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.
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.
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
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.
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.
Decorator Pattern – Real Time Examples Decorator Streams:
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
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.
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.
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.
Composite Pattern • Makes use of the following features: • Generics • Properties • Struct • Indexers • Implicit Typing • Initializers • Anonymous Types
Composite Pattern - Real Time Examples • TreeNodeCollectionclass & ToolStripclass • CompositeControl class • Files and Folders • Organizational Tree • ArithmethicExpresssion • Generic containers
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.
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.
Façade Pattern - Structure Client Facade Subsystem
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.
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
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.
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.
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.
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
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.
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.
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).
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