RSS

Bridge Design Pattern

Download the working example demo code in java from my GIT repository -https://github.com/premaseem/designPatterns/tree/4bb9beca7bab5b5e71d02b76e4f1ad48fce4aca6/ZipDownloadableProjects

Example Code description :
TV and remote are 2 separate entities. As an architect of remote one way is to abstract all remote in an interface and develop it, however the challenge is in the way both TV and remote development is getting mixed or interlocked – in technical terms getting tightly coupled. Changes in one might effect the another. So to solve it, We have created a bridge between TV and remote. Thus decoupled TV and Remote. Please download example and try on your own.

bridge2

Definition :
“Decouple an abstraction from its implementation so that the two can vary independently” is the intent for bridge design pattern as stated by GoF.
Bridge design pattern is a modified version of the notion of “prefer composition over inheritance”.Decouple implentation from interface and hiding implementation details from client is the essence of bridge design pattern.

Bridge is used where we need to decouple an abstraction from its implementation so that the two can vary independently.

This type of design pattern comes under structural pattern as this pattern decouples implementation class and abstract class by providing a bridge structure between them.

This pattern involves an interface which acts as a bridge which makes the functionality of concrete classes independent from interface implementer classes. Both types of classes can be altered structurally without affecting each other.

Elements of Bridge Design Pattern

  • Abstraction – core of the bridge design pattern and defines the crux. Contains a reference to the implementer.
  • Refined Abstraction – Extends the abstraction takes the finer detail one level below. Hides the finer elements from implemetors.
  • Implementer – This interface is the higer level than abstraction. Just defines the basic operations.
  • Concrete Implementation – Implements the above implementer by providing concrete implementation.

bridge

Summary of Bridge Design Pattern

  • Creates two different hierarchies. One for abstraction and another for implementation.
  • Avoids permanent binding by removing the dependency between abstraction and implementation.
  • We create a bridge that coordinates between abstraction and implementation.
  • Abstraction and implementation can be extended separately.
  • Should be used when we have need to switch implementation at runtime.
  • Client should not be impacted if there is modification in implementation of abstraction.
  • Best used when you have multiple implementations.

bridgeColor

Bridge Vs Adapter Design Pattern

The adapter design pattern helps it two incompatible classes to work together. But, bridge design pattern decouples the abstraction and implementation by creating two different hierarchies.

 
 

Tags: , ,

Is MVC one of the GoF (Gang-of-Four) patterns?

MVC is not one of the GoF patterns. They are not at the same level. MVC is what is called an architectural pattern while GoF patterns are design patterns. Basically MVC is a compound pattern (combination of more than 1 design pattern), that means it is a guide line and could be implemented using several other design patterns.

However, when implementing MVC you can take advantage of existing patterns. Take the Head First Design Patterns book they build MVC using Strategy, Composite, and Observer pattern. And I’m sure that there exists other implementations of the MVC pattern using other design patterns. I have also seen MVC being done using the Command pattern.
Needless to say, even though MVC is not a GoF pattern, it is still a very useful one. GoF patterns are only a few of all existing patterns out there.

 
Leave a comment

Posted by on September 18, 2014 in Design Patterns

 

Tags: ,

Proxy Design Pattern

Download the working example demo code in java from my GIT repository -https://github.com/premaseem/designPatterns/tree/4bb9beca7bab5b5e71d02b76e4f1ad48fce4aca6/ZipDownloadableProjects
Code example Description :
Doctors are busy and uses proxies / surrogates or say assistant doctors, unless they are not needed. For initial investigation  senior doctor or surgeon is not required, hence they make you to interact with their proxy/assistant doctor. However, for operation or consulting they take the charge (replaces the proxy).

Proxy

Proxy means ‘in place of’. In attendance roll call, we give proxy for our friends in college right? ‘Representing’ or ‘in place of’ or ‘on behalf of’ are literal meanings of proxy and that directly explains proxy design pattern. It is one of the simplest and straight forward design pattern.

Intent :
Provide a surrogate or placeholder for another object to control access to it.
Use an extra level of indirection to support distributed, controlled, or intelligent access.
Add a wrapper and delegation to protect the real component from undue complexity.

Problem :
You need to support resource-hungry objects, and you do not want to instantiate such objects unless and until they are actually requested by the client.

Possible Usage Scenarios :
Remote Proxy – Represents an object locally which belongs to a different address space. Think of an ATM implementation, it will hold proxy objects for bank information that exists in the remote server. RMI is an example of proxy implmenetation for this type in java.
Virtual Proxy – In place of a complex or heavy object use a skeleton representation. When an underlying image is huge in size, just represent it using a virtual proxy object and on demand load the real object. You feel that the real object is expensive in terms of instantiation and so without the real need we are not going to use the real object. Until the need arises we will use the virtual proxy.
Protection Proxy – Are you working on a MNC? If so, you might be well aware of the proxy server that provides you internet. Saying more than provides, the right word is censores internet. The management feels its better to censor some content and provide only work related web pages. Proxy server does that job. This is a type of proxy design pattern.
Smart Reference – Just we keep a link/reference to the real object a kind of pointer.

Structure

By defining a Subject interface, the presence of the Proxy object standing in place of the RealSubject is transparent to the client.

ProxyStructure

Discussion :
Design a surrogate, or proxy, object that: instantiates the real object the first time the client makes a request of the proxy, remembers the identity of this real object, and forwards the instigating request to this real object. Then all subsequent requests are simply forwarded directly to the encapsulated real object.

There are four common situations in which the Proxy pattern is applicable.
A virtual proxy is a placeholder for “expensive to create” objects. The real object is only created when a client first requests/accesses the object.
A remote proxy provides a local representative for an object that resides in a different address space. This is what the “stub” code in RPC and CORBA provides.
A protective proxy controls access to a sensitive master object. The “surrogate” object checks that the caller has the access permissions required prior to forwarding the request.
A smart proxy interposes additional actions when an object is accessed. Typical uses include:

Important Points:
A proxy may hide information about the real object to the client.
A proxy may perform optimization like on demand loading.
A proxy may do additional house-keeping job like audit tasks.
Proxy design pattern is also known as surrogate design pattern.

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.
Consider defining a Factory that can encapsulate the decision of whether a proxy or original object is desirable.
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.

Rules of thumb :
Adapter provides a different interface to its subject. Proxy provides the same interface. Decorator provides an enhanced interface.
Decorator and Proxy have different purposes but similar structures. Both describe how to provide a level of indirection to another object, and the implementations keep a reference to the object to which they forward requests.

 
 

Tags: , ,

Difference between “implements Runnable” and “extends Thread” in java

In java language, as we all know that there are two ways to create threads. One using Runnable interface and another by extending Thread class.

Thread

Here are some of my thoughts on whether I should use Thread or Runnable for implementing task in Java, though you have another choice as “Callable” for implementing thread which we will discuss later.

1) Java doesn’t support multiple inheritance, which means you can only extend one class in Java so once you extended Thread class you lost your chance and can not extend or inherit another class in Java.

2) In Object oriented programming extending a class generally means adding new functionality, modifying or improving behaviors. If we are not making any modification on Thread than use Runnable interface instead.

3) Runnable interface represent a Task which can be executed by either plain Thread or Executors or any other means. so logical separation of Task as Runnable than Thread is good design decision.

4) Separating task as Runnable means we can reuse the task and also has liberty to execute it from different means. since you can not restart a Thread once it completes. again Runnable vs Thread for task, Runnable is winner.

5) Java designer recognizes this and that’s why Executors accept Runnable as Task and they have worker thread which executes those task.

6) Inheriting all Thread methods are additional overhead just for representing a Task which can can be done easily with Runnable.

7) Thread class approach, you must have to create separate instance for every thread access. Hence different memory is allocated for every class instances.

8) Coding to an interface rather than to implementation. This makes your software/application easier to extend. In other words, your code will work with all the interface’s subclasses, even ones that have not been created yet.

9)Interface inheritance (implements) is preferable – This makes your code is loosely coupling between classes/objects.

Note : Thread class internally implements the Runnable interface

 
Leave a comment

Posted by on September 17, 2014 in Java Tips

 

Tags: , ,

Passionate Coder

Do you have passion for Coding ?

Meet my friend who is a Passionate Coder.

passionateCoder

 
Leave a comment

Posted by on September 17, 2014 in Computers, Leadership, Life

 

Tags:

Template Method Design Pattern

Download the working example demo code in java from my GIT repository -https://github.com/premaseem/designPatterns/tree/4bb9beca7bab5b5e71d02b76e4f1ad48fce4aca6/ZipDownloadableProjects

Example Code Briefings : Template Method Fruit Juice extraction example defines a recipe (with exact steps and quantity) to prepare the drink which is kept in the extract class. However the flavor of the fruit Juice can be changed by it subclasses by overriding (which is defined as hooks/abstractor in parent abstract class).

Intent:
Define the skeleton of an algorithm in an operation, deferring some steps to client subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.
Base class declares algorithm ‘placeholders’, and derived classes implement the placeholders.

Problem:
Two different components have significant similarities, but demonstrate no reuse of common interface or implementation. If a change common to both components becomes necessary, duplicate effort must be expended.

Definition:
Template method design pattern is to define an algorithm as skeleton of operations and leave the details to be implemented by the child classes. The overall structure and sequence of the algorithm is preserved by the parent class.
The component designer decides which steps of an algorithm are invariant (or standard), and which are variant (or customizable). The invariant steps are implemented in an abstract base class, while the variant steps are either given a default implementation, or no implementation at all. The variant steps represent “hooks”, or “placeholders”, that can, or must, be supplied by the component’s client in a concrete derived class.

The component designer mandates the required steps of an algorithm, and the ordering of the steps, but allows the component client to extend or replace some number of these steps.

Template Method is used prominently in frameworks. Each framework implements the invariant pieces of a domain’s architecture, and defines “placeholders” for all necessary or interesting client customization options. In so doing, the framework becomes the “center of the universe”, and the client customizations are simply “the third rock from the sun”. This inverted control structure has been affectionately labelled “the Hollywood principle” – “don’t call us, we’ll call you”.

Template Method scheme

Structure:
Template Method scheme
The implementation of template_method() is: call step_one(), call step_two(), and call step_three(). step_two() is a “hook” method – a placeholder. It is declared in the base class, and then defined in derived classes. Frameworks (large scale reuse infrastructures) use Template Method a lot. All reusable code is defined in the framework’s base classes, and then clients of the framework are free to define customizations by creating derived classes as needed.

Example:
Daily routine of a worker.

Template Method example

Rules of thumb:
Strategy is like Template Method except in its granularity.
Template Method uses inheritance to vary part of an algorithm. Strategy uses delegation to vary the entire algorithm.
Strategy modifies the logic of individual objects. Template Method modifies the logic of an entire class.
Factory Method is a specialization of Template Method.

 
 

Tags: , ,

Composite Design Pattern

Download the working example demo code in java from my GIT repository -https://github.com/premaseem/designPatterns/tree/4bb9beca7bab5b5e71d02b76e4f1ad48fce4aca6/ZipDownloadableProjects

Intent:
Compose objects into tree structures to represent whole-part hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
Recursive composition
“Directories contain entries, each of which could be a directory.”
1-to-many “has a” up the “is a” hierarchy

What is Whole-part Hierarchy :
A system consists of subsystems or components. Components can further be divided into smaller components. Further smaller components can be divided into smaller elements. This is a part-whole hierarchy.
 
Problem:
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. Having to query the “type” of each object before attempting to process it is not desirable.
 

Tree for Composite
When we get a recursive structure the obvious choice for implementation is a tree. In composite design pattern, the part-whole hierarchy can be represented as a tree. Leaves (end nodes) of a tree being the primitive elements and the tree being the composite structure.
 composite1
 
Uml Design for Composite Pattern

Component: (structure)

    Component is at the top of hierarchy. It is an abstraction for the composite.
    It declares the interface for objects in composition.
    (optional) defines an interface for accessing a component’s parent in the recursive structure, and implements it if that’s appropriate.

Leaf: (primitive blocks)

    The end nodes of the tree and will not have any child.
    Defines the behaviour for single objects in the composition

Composite: (group)

    Consists of child components and defines behaviour for them
    Implements the child related operations.
 composite

 
Important Points:
Recursive formation and tree structure for composite should be noted.
Clients access the whole hierarchy through the components and they are not aware about if they are dealing with leaf or composites.
Importance of composite pattern is, the group of objects should be treated similarly as a single object.
Being able to treat a heterogeneous collection of objects atomically (or transparently) requires that the “child management” interface be defined at the root of the Composite class hierarchy (the abstract Component class). However, this choice costs you safety, because clients may try to do meaningless things like add and remove objects from leaf objects. On the other hand, if you “design for safety”, the child management interface is declared in the Composite class, and you lose transparency because leaves and Composites now have different interfaces.

compsiteStructure

Rules of thumb
Composite and Decorator have similar structure diagrams, reflecting the fact that both rely on recursive composition to organize an open-ended number of objects.
Decorator is designed to let you add responsibilities to objects without subclassing. Composite’s focus is not on embellishment but on representation. These intents are distinct but complementary. Consequently, Composite and Decorator are often used in concert.

 
Leave a comment

Posted by on September 15, 2014 in Design Patterns

 

Tags: , ,

 
Follow

Get every new post delivered to your Inbox.

Join 1,067 other followers

%d bloggers like this: