Design Pattern - Structural Patterns

<< Creational Patterns : Previous blog 

Structural Patterns

Structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities. These design patterns help us on similar programming structure in application and help us in application wide coding standard. 
Adapter:
the adapter pattern (often referred to as the wrapper pattern or simply a wrapper) is a design pattern that translates one interface for a class into a compatible interface. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface. The adapter translates calls to its interface into calls to the original interface, and the amount of code necessary to do this is typically small. The adapter is also responsible for transforming data into appropriate forms. For instance, if multiple boolean values are stored as a single integer (i.e. flags) but the client requires individual boolean values, the adapter would be responsible for extracting the appropriate values from the integer value. Another example is transforming the format of dates (e.g. YYYYMMDD to MM/DD/YYYY or DD/MM/YYYY).
Example: Adapter Pattern is useful where we want to do integration from one format to another
  > java.util.Arrays#asList()
  > java.io.InputStreamReader(InputStream) (returns a Reader)
  > java.io.OutputStreamWriter(OutputStream) (returns a Writer)


Facade:
A facade Pattern is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can:
  • make a software library easier to use, understand and test, since the facade has convenient methods for common tasks;
  • make the library more readable, for the same reason;
  • reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system;
  • wrap a poorly designed collection of APIs with a single well-designed API (as per task needs).
Example: Facade pattern is used to make any library classes and It help us to build module as service. 
  > javax.servlet.http.HttpSession
 > javax.servlet.http.HttpServletRequest
 > javax.servlet.http.HttpServletResponse
 > javax.faces.context.ExternalContext


Proxy:
A proxy, in its most general form, is a class functioning as an interface to do something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.
A well-known example of the proxy pattern is a reference counting pointer object.
In situations where multiple copies of a complex object must exist, the proxy pattern can be adapted to incorporate the flyweight pattern in order to reduce the application's memory footprint. Typically, one instance of the complex object and multiple proxy objects are created, all of which contain a reference to the single original complex object. Any operations performed on the proxies are forwarded to the original object. Once all instances of the proxy are out of scope, the complex object's memory may be deallocated.
Example: This pattern is useful to create surrogate service, where client does not know about actual implementation.  java.rmi.* service uses Proxy pattern to communicate on network.

Bridge:
The bridge pattern is meant to "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.
When a class varies often, the features of object-oriented programming become very useful because changes to a program's code can be made easily with minimal prior knowledge about the program. The bridge pattern is useful when both the class as well as what it does vary often. The class itself can be thought of as the implementation and what the class can do as the abstraction. The bridge pattern can also be thought of as two layers of abstraction.
The bridge pattern is often confused with the adapter pattern. In fact, the bridge pattern is often implemented using the class "adapter pattern", e.g. in the Java code below.
Example: The Bridge pattern is an application of the old advice, "prefer composition over inheritance". It becomes handy when you must subclass different times in ways that are orthogonal with one another. Say you must implement a hierarchy of colored shapes. You wouldn't subclass Shape with Rectangle and Circle and then subclass Rectangle with RedRectangle, BlueRectangle and GreenRectangle and the same for Circle, would you? You would prefer to say that each Shape has a Color and to implement a hierarchy of colors, and that is the Bridge Pattern.

Composite:
Composite pattern is a partitioning design pattern. The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.

Component
  • is 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, and implements it if that's appropriate
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
Example: This pattern is used in making Rule engine or validation pattern, where composite and single rule can be used in same way.

    Decorator:
    the decorator pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.The decorator pattern can be used to extend (decorate) the functionality of a certain object statically, or in some cases at run-time, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new decorator class that wraps the original class. This wrapping could be achieved by the following sequence of steps:
    1. Subclass the original "Decorator" class into a "Component" class (see UML diagram);
    2. In the Decorator class, add a Component pointer as a field;
    3. Pass a Component to the Decorator constructor to initialize the Component pointer;
    4. In the Decorator class, redirect all "Component" methods to the "Component" pointer; and
    5. In the ConcreteDecorator class, override any Component method(s) whose behavior needs to be modified.
    This pattern is designed so that multiple decorators can be stacked on top of each other, each time adding a new functionality to the overridden method(s).
    The decorator pattern is an alternative to subclassing. Subclassing adds behavior at compile time, and the change affects all instances of the original class; decorating can provide new behavior at run-time for individual objects.
    This difference becomes most important when there are several independent ways of extending functionality. In some object-oriented programming languages, classes cannot be created at runtime, and it is typically not possible to predict, at design time, what combinations of extensions will be needed. This would mean that a new class would have to be made for every possible combination. By contrast, decorators are objects, created at runtime, and can be combined on a per-use basis. The I/O Streams implementations of both Java and the .NET Framework incorporate the decorator pattern.
    Example for this: Java collections object using Collections.synchronized() method to synchronize the collection at run time. All subclasses of java.io.InputStreamOutputStreamReader and Writer have a constructor taking an instance of same type. Another good example is javax.servlet.http.HttpServletRequestWrapper and HttpServletResponseWrapper.

    Flyweight:
    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. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used.
    A classic example usage of the flyweight pattern is the data structures for graphical representation of characters in a word processor. It might be desirable to have, for each character in a document, a glyph object containing its font outline, font metrics, and other formatting data, but this would amount to hundreds or thousands of bytes for each character. Instead, for every character there might be a reference to a flyweight glyph object shared by every instance of the same character in the document; only the position of each character (in the document and/or the page) would need to be stored internally. Another example is string interning.
    In other contexts the idea of sharing identical data structures is called hash consing.
    Sample Code for Fly weight pattern.
    Example :  This pattern is used with method overloading and  java.lang.Integer#valueOf(int) (also on BooleanByteCharacterShort and Long) is example of this.

    Next >>  Behavioural Patterns.

    8 comments:

    1. Excellent post. I was always checking this blog, and I’m impressed! Extremely useful info specially the last part, I care for such information a lot. I was exploring this particular info for a long time. Thanks to this blog my exploration has ended.
      If you want Digital Marketing Serives :-
      Digital marketing Service in Delhi
      SMM Services
      PPC Services in Delhi
      Website Design & Development Packages
      SEO Services PackagesLocal SEO services
      E-mail marketing services
      YouTube plans

      ReplyDelete
    2. Nice Blog Thanks for sharing your valuable information If Any one who want to learn java core to advance contact us on 9311002620 or visit https://www.htsindia.com/Courses/JAVA/core-java-training-course-institute

      ReplyDelete
    3. H2Kinfosys is offering Selenium online training with Selenium Webdriver, and Junit. Learn selenium Java online from our software testing experts.

      ReplyDelete
    4. Why Should You Opt For Selenium Automation Testing?

      H2Kinfosys is offering Selenium online training with Selenium Webdriver, and Junit. Learn selenium Java online from our software testing experts.

      ReplyDelete
    5. This comment has been removed by the author.

      ReplyDelete
    6. The latest version of selenium is the Selenium Webdriver which improves functional test coverage. Learn Selenium Automation Testing to drive into the IT field.

      ReplyDelete
    7. great article... This is very impotent information for us.if any one want to learn digital marketing course in cheap price contact us on 9311002620 or https://www.htsindia.com/Courses/Digital-Marketing/digital-marketing-training-course

      ReplyDelete

    8. I am really very happy to visit your blog. Directly I am found which I truly need. please visit our website for more information
      Data visualization Service in USA

      ReplyDelete