Free Essay

Structure Sesign Pattern

In:

Submitted By piusharma10
Words 3378
Pages 14
Introduction

Design Patterns
In Software Engineering we use different design pattern as a general solution to commonly occurring design problems. Originally 23 design patterns were introduced by 4 authors in their book, who came to be known as “Gang of four.”
The 3 Basic types of design patterns are:
Creational patterns
Structural patterns
Behavioural patterns
In this term paper we’ll discuss about structural design patterns.

Structural patterns
Structural Design Patterns are design patterns that deals with Class and Object composition. It does the following things:
1. It uses the concept of interface by using inheritance.
2. It defines object in such ways as to use them for multiple purpose.
3. It helps to relate various entities using different means by finding their relationship with each other.
Various types of Structural Design Patterns are given below:
Adapter: It acts as a translator to match interface between two incompatible classes.
Bridge: Separates abstract interface from its implementation, which provides a cleaner implementation of real-world objects and allows the implementation details to be changed easily.
Composite: used when creating hierarchical object models, this allows clients to treat individual objects uniformly.
Decorator: It extends the functionality of individual objects by wrapping them with one or more decorator classes. These decorators can modify existing members and add new methods and properties at run-time.
Facade: It is used to provide a high-level interface that makes the subsystem easier to use. It helps to create a unified interface to a set of interfaces in the subsystem.
Flyweight: It is used to minimize resource usage when working with very large no. of objects.
Proxy: In its most general form it is an interface to something else (Subject class).It can be used when we don’t want to access resource directly.
Private class data: Restricts accessor/mutator access

Now let’s discuss about each structural pattern in detail.

Adapter Pattern

Motivation
The adapter pattern is adapting between classes and objects. Like any adapter in the real world it is used to be an interface, a bridge between two objects. In real world we have adapters for power supplies, adapters for camera memory cards, and so on. Probably everyone have seen some adapters for memory cards. If you can’t plug in the camera memory in your laptop you can use and adapter. You plug the camera memory in the adapter and the adapter in to laptop slot. That's it, it's really simple.
It's the same in software development. In a situation when you have some class expecting some type of object and you have an object offering the same features.
Intent
It converts the interface of a class into another interface clients expect.
Adapter lets classes work together, that could not otherwise because of incompatible interfaces.

Implementation The figure below shows a UML class diagram for the Adapter Pattern:

Participants The classes/objects participating in adapter pattern:
Target - defines the domain-specific interface that Client uses.
Adapter - adapts the interface Adaptee to the Target interface.
Adaptee - defines an existing interface that needs adapting.
Client - collaborates with objects conforming to the Target interface.
Non Software Examples of Adapter Patterns : Power Supply Adapters, card readers and adapters, ...

Implementation
Objects Adapters - Based on Delegation and single inheritance
Objects Adapters are the example of the adapter pattern. It uses composition, the Adaptee delegates the calls to Adaptee (opossed to class adapters which extends the Adaptee). This behaviour gives us a few advantages over the class adapters. The main advantage is that the Adapter adapts not only the Adpatee but all its subclasses.
Class Adapters - Based on Multiple Inheritance
Class adapters can be implemented in languages supporting multiple inheritance.Thus, such adapters cannot be easy implemented in Java, C# or VB.NET.
Class adapter uses inheritance instead of composition. It means that instead of delegating the calls to the Adaptee, it subclasses it. In conclusion it must subclass both the Target and the Adaptee. There are advantages and disadvantages:
It adapts the specific Adaptee class. The class it extends. If that one is subclassed it cannot be adapted by the existing adapter.

Bridge Pattern
Intent
The intent of this pattern is to decouple abstraction from implementation so that the two can vary independently.

Implementation
The figure below shows a UML class diagram for the Bridge Pattern: Participants
Abstraction - Abstraction defines abstraction interface.
AbstractionImpl - Implements the abstraction interface using a reference to an object of type Implementor.
Implementor - Implementor defines the interface for implementation classes. This interface does not need to correspond directly to abstraction interface and can be very different. Abstraction imp provides an implementation in terms of operations provided by Implementor interface.
ConcreteImplementor1, ConcreteImplementor2 - Implements the Implementor interface.

Applicability

The bridge pattern applies when there is a need to avoid permanent binding between an abstraction and an implementation and when the abstraction and implementation need to vary independently. Using the bridge pattern would leave the client code unchanged with no need to recompile the code.

Related Patterns
Abstract Factory Pattern - An Abstract Factory pattern can be used create and configure a particular Bridge, for example a factory can choose the suitable concrete implementor at runtime.
Known Uses: Graphical User Interface Frameworks
Graphical User Interface Frameworks use the bridge pattern to separate abstractions from platform specific implementation. For example GUI frameworks separate a Window abstraction from a Window implementation for Linux or Mac OS using the bridge pattern.

Composite Pattern

Motivation
There are times when a program needs to manipulate a tree data structure and it is necessary to treat both Branches as well as Leaf Nodes uniformly. For example a program that manipulates a file system. A file system is a tree structure that contains Branches which are Folders as well as Leaf nodes which are Files. In such cases Bridge pattern is used.

Intent
The intent of this pattern is to compose objects into tree structures to represent part-whole hierarchies.
Composite lets clients treat individual objects and compositions of objects uniformly.

Implementation
The figure below shows a UML class diagram for the Composite Pattern:

Participants
Component - Component is the abstraction for leafs and composites. It defines the interface that must be implemented by the objects in the composition. For example a file system resource defines move, copy, rename, and getSize methods for files and folders.
Leaf - Leafs are objects that have no children. They implement services described by the Component interface. For example a file object implements move, copy, rename, as well as getSize methods which are related to the Component interface.
Composite - A Composite stores child components in addition to implementing methods defined by the component interface. Composites implement methods defined in the Component interface by delegating to child components. In addition composites provide additional methods for adding, removing, as well as getting components.
Client - The client manipulates objects in the hierarchy using the component interface.

A client has a reference to a tree data structure and needs to perform operations on all nodes independent of the fact that a node might be a branch or a leaf. The client simply obtains reference to the required node using the component interface, and deals with the node using this interface; it doesn’t matter if the node is a composite or a leaf.

Applicability
The composite pattern applies when there is a part-whole hierarchy of objects and a client needs to deal with objects uniformly regardless of the fact that an object might be a leaf or a branch.

Example - Graphics Drawing Editor.
In graphics editors a shape can be basic or complex. An example of a simple shape is a line, where a complex shape is a rectangle which is made of four line objects. Since shapes have many operations in common such as rendering the shape to screen, and since shapes follow a part-whole hierarchy, composite pattern can be used to enable the program to deal with all shapes uniformly.

Implementation
Graphics Editors use composite pattern to implement complex and simple graphics as previously explained.
File System implementations use the composite design pattern.
Consequences
The composite pattern defines class hierarchies consisting of primitive objects and composite objects. Primitive objects can be composed into more complex objects, which in turn can be composed.
Clients treat primitive and composite objects uniformly through a component interface which makes client code simple.
Adding new components can be easy and client code does not need to be changed since client deals with the new components through the component interface.

Related Patterns
Decorator Pattern - 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.

Decorator Pattern

Motivation
Extending an object’s functionality can be done at compile time by using inheritance however it might be necessary to extend an object’s functionality dynamically as an object is used.
For example to extend the functionality of the graphical window for example by adding a frame to the window, would require extending the window class to create a FramedWindow class. To create a framed window it is necessary to create its object. It would be impossible to start with a plain window and to extend its functionality at runtime to become a framed window.

Intent
The intent of this pattern is to add additional responsibilities dynamically to an object.

Implementation
The figure below shows a UML class diagram for the Decorator Pattern:

Participants
Component - Interface for objects that can have responsibilities added to them dynamically.
ConcreteComponent - Defines an object to which additional responsibilities can be added.
Decorator - Maintains a reference to a Component object and defines an interface that conforms to Component's interface.
Concrete Decorators - Concrete Decorators extend the functionality of the component by adding state or adding behavior.
Implementation
The decorator pattern applies when there is a need to dynamically add as well as remove responsibilities to a class, and when subclassing would be impossible due to the large number of subclasses that could result.

Applicability
Example - Extending capabilities of a Graphical Window at runtime

In Graphical User Interface toolkits windows behaviors can be added dynamically by using the decorator design pattern.
Related Patterns
Adapter Pattern - A decorator is different from an adapter in that a decorator changes object's responsibilities, while an adapter changes an object interface.
Composite Pattern - A decorator can be viewed as a degenerate composite with only one component. However, a decorator adds additional responsibilities.
Consequences
Decoration is more convenient for adding functionalities to objects instead of entire classes at runtime. With decoration it is also possible to remove the added functionalities dynamically.
Decoration adds functionality to objects at runtime which would make debugging system functionality harder.

Flyweight Pattern

Motivation
Some programs require a large number of objects that have some shared state among them. Consider for example a game of war, were there is a large number of soldier objects; a soldier object maintain the graphical representation of a soldier, soldier behavior such as motion, and firing weapons, location etc. Creating a large number of soldier objects is a necessity but it would incur a huge memory cost. In such case Flyweight pattern is used.

Intent
The intent of this pattern is to use sharing to support a large number of objects that have part of their internal state in common where the other part of state can vary.

Implementation
The figure below shows a UML class diagram for the Flyweight Pattern: Participants
Flyweight - Declares an interface through which flyweights can receive and act on extrinsic state.
ConcreteFlyweight - Implements the Flyweight interface and stores intrinsic state. A ConcreteFlyweight object must be sharable. The Concrete flyweight object must maintain state that it is intrinsic to it, and must be able to manipulate state that is extrinsic. In the war game example graphical representation is an intrinsic state, where location and health states are extrinsic. Soldier moves, the motion behavior manipulates the external state (location) to create a new location.
FlyweightFactory - The factory creates and manages flyweight objects. In addition the factory ensures sharing of the flyweight objects. The factory maintains a pool of different flyweight objects and returns an object from the pool if it is already created, adds one to the pool and returns it in case it is new. In the war example a Soldier Flyweight factory can create two types of flyweights: a Soldier flyweight, as well as a Colonel Flyweight. When the Client asks the Factory for a soldier, the factory checks to see if there is a soldier in the pool, if there is, it is returned to the client, if there is no soldier in pool, a soldier is created, added to pool, and returned to the client, the next time a client asks for a soldier, the soldier created previously is returned, no new soldier is created.
Client - A client maintains references to flyweights in addition to computing and maintaining extrinsic state

A client needs a flyweight object; it calls the factory to get the flyweight object. The factory checks a pool of flyweights to determine if a flyweight object of the requested type is in the pool, if there is, the reference to that object is returned. If there is no object of the required type, the factory creates a flyweight of the requested type, adds it to the pool, and returns a reference to the flyweight. The flyweight maintains a state that is shared among the large number of objects that we have created the flyweight for and provides methods to manipulate external state (State that vary from object to object and is not common among the objects we have created the flyweight for).

Applicability
The flyweight pattern applies to a program using a huge number of objects that have part of their internal state in common where the other part of state can vary. The pattern is used when the larger part of the object’s state can be made extrinsic (external to that object).

Consequences
Flyweight pattern saves memory by sharing flyweight objects among clients. The amount of memory saved generally depends on the number of flyweight categories saved (for example a soldier category and a lieutenant category as discussed earlier).

Related Patterns
Factory and Singleton patterns - Flyweights are usually created using a factory and the singleton is applied to that factory so that for each type or category of flyweights a single instance is returned.
State and Strategy Patterns - State and Strategy objects are usually implemented as Flyweights.

Proxy Pattern

Motivation
Sometimes we need the ability to control the access to an object. For example if we need to use only a few methods of some costly objects we'll initialize those objects when we need them entirely. Until that point we can use some light objects exposing the same interface as the heavy objects. These light objects are called proxies.
This ability to control the access to an object can be required for a variety of reasons: controlling when a costly object needs to be instantiated and initialized, giving different access rights to an object, as well as providing a sophisticated means of accessing and referencing objects running in other processes, on other machines.
Intent
The intent of this pattern is to provide a Placeholder for an object to control references to it.

Structure and Implementation
The figure below shows a UML class diagram for the Proxy Pattern: Participants
Subject - Interface implemented by the RealSubject and representing its services. The interface must be implemented by the proxy as well so that the proxy can be used in any location where the RealSubject can be used.
Proxy: Maintains a reference that allows the Proxy to access the RealSubject.
Also it implements the same interface implemented by the RealSubject so that the Proxy can be substituted for the RealSubject.
Controls access to the RealSubject and may be responsible for its creation and deletion.
RealSubject - The real object that the proxy represents.
A client obtains a reference to a Proxy, the client then handles the proxy in the same way it handles RealSubject and thus invoking the method doSomething(). At that point the proxy can do different things prior to invoking RealSubject’s method. The client might create a RealSubject object at that point, perform initialization, check permissions of the client to invoke the method, and then invoke the method on the object.

Applicability
The Proxy design pattern is applicable when there is a need to control access to an Object, as well as when there is a need for a sophisticated reference to an Object. Common Situation where the proxy pattern is applicable is:
Virtual Proxies: delaying the creation and initialization of expensive objects until needed, where the objects are created on demand (For example creating the RealSubject object only when the doSomething method is invoked).
Protection Proxies: where a proxy controls access to RealSubject methods, by giving access to some objects while denying access to others.
Related Patterns
Adapter Design Pattern - The adapter implements a different interface to the object it adapts where a proxy implements the same interface as its subject.
Decorator Design Pattern - A decorator implementation can be the same as the proxy however a decorator adds responsibilities to an object while a proxy controls access to it.

Facade Design Pattern

Motivation
When a segment of the client community needs a simplified interface to the overall functionality of a complex subsystem.
Intent
It provides 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.

Structure
The Facade defines a unified, higher level interface to a subsystem that makes it easier to use. Consumers encounter a Facade when ordering from a catalog. The consumer calls one number and speaks with a customer service representative. The customer service representative acts as a Facade, providing an interface to the order fulfillment department, the billing department, and the shipping department.

Steps:
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
Difference
Facade defines a new interface, whereas Adapter uses an old interface
Whereas Flyweight shows how to make lots of little objects, Facade shows how to make a single object represent an entire subsystem.

Private Class Data

Motivation
A class may expose its attributes (class variables) to manipulation when manipulation is no longer desirable, e.g. after construction. Using the private class data design pattern prevents that undesirable manipulation.
The motivation for this design pattern comes from the design goal of protecting class state by minimizing the visibility of its attributes (data).

Intent
It control write access to class attributes
Separate data from methods that use it
Encapsulate class data initialization.

Structure
The private class data design pattern solves the problems above by extracting a data class for the target class and giving the target class instance an instance of the extracted data class.

Create data class and move to data class all attributes that need hiding.
Create in main class instance of data class. Main class must initialize data class through the data class's constructor.
Consequences
The private class data design pattern seeks to reduce exposure of attributes by limiting their visibility.It reduces the number of class attributes by encapsulating them in single Data object.
It allows the class designer to remove write privilege of attributes that are intended to be set only during construction, even from methods of the target class.

Conclusion

We have presented advantages for data structures implementation of the following design patterns: Flyweight, Bridge, Adapter, Decorator, Composite, Façade, Private Data class. Structural patterns focus on the composition of classes and objects into larger structures. They deal with run-time compositions that are more dynamic than traditional multiple inheritance, object sharing and interface adaptation, and dynamic addition of responsibilities to objects.

References: http://sourcemaking.com/design_patterns/structural_patterns http://www.oodesign.com/design-principles.html http://www.gofpatterns.com/design-patterns/module5/intro-structural-designPatterns.php http://www.cs.ubbcluj.ro/~vniculescu/didactic/SD_DID/structuralDesignPatterns.pdf
Book: Design Patterns By Rupinder Kaur

Similar Documents