Flyweight Design Pattern

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

Flyweight is used when there is a need to create high number of objects of almost similar nature.

For example assume we are working with an application that maps stars from universe. In this application if we are going to create an object for every star then think of it how much memory we will need. There could be max 10 types of stars (intrinsic) which would be placed at different coordinates (extrinsic). The idea it to create only 10 object and place them at different coordinates directed by client. This is really handy with video games and graphic application especially on Mobile devices where memory is critical.

High number of objects consumes high memory and flyweight design pattern gives a solution to reduce the load on memory by sharing objects. Each “flyweight” object is divided into two pieces: the state-dependent (extrinsic) part, and the state-independent (intrinsic) part. Intrinsic state is stored (shared) in the Flyweight object. Extrinsic state is stored or computed by client objects, and passed to the Flyweight when its operations are invoked.

Intent :
Use sharing to support large numbers of fine-grained objects efficiently.
Problem

Designing objects down to the lowest levels of system “granularity” provides optimal flexibility, but can be unacceptably expensive in terms of performance and memory usage.

 

When to Use Flyweight Design Pattern

  • Need to create large number of objects.
  • Because of the large number when memory cost is a constraint.
  • When most of the object attributes can be made external and shared.
  • The application must not mandate unique objects, as after implementation same object will be used repeatedly.
  • Its better when extrinsic state can be computed rather than stored. (explained below)

Check list
  1. Ensure that object overhead is an issue needing attention, and, the client of the class is able and willing to absorb responsibility realignment.
  2. Divide the target class’s state into: shareable (intrinsic) state, and non-shareable (extrinsic) state.
  3. Remove the non-shareable state from the class attributes, and add it the calling argument list of affected methods.
  4. Create a Factory that can cache and reuse existing class instances.
  5. The client must use the Factory instead of the new operator to request objects.
  6. The client (or a third party) must look-up or compute the non-shareable state, and supply that state to class methods.

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.

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.

State design Pattern

Download the working example demo code in java from my GIT repository –https://github.com/premaseem/designPatterns/blob/master/ZipDownloadableProjects/StatePatternMedicalTreatmentExample.zip

To see code visit diff link:https://github.com/premaseem/designPatterns/commit/821595e18f1c9c04f0b2c47cacb03278c0485511

The state pattern, which closely resembles Strategy Pattern, is a behavioral software design pattern, also known as the objects for states pattern. This pattern is used in computer programming to encapsulate varying behavior for the same routine based on an object’s state object. This can be a cleaner way for an object to change its behavior at runtime without resorting to large monolithic conditional statements.
In State pattern, we create objects which represent various states and a context object whose behavior varies as its state object changes.

Problem solved by State pattern

A monolithic object’s behavior is a function of its state, and it must change its behavior at run-time depending on that state. Or, an application is characterixed by large and numerous case statements that vector flow of control based on the state of the application.

Different between State and Strategy

Strategy Pattern is used when the whole algorithm is changed to another algorithm and the client is responsible for that, whereas, in State Pattern, the class itself manages the strategy based on the state. Two patterns are pretty similar in practice, and the defining difference between them tends to vary depending on who you ask. Some popular choices are:
States store a reference to the context object that contains them. Strategies do not.
States are allowed to replace themselves (IE: to change the state of the context object to something else), while Strategies are not.
Strategies are passed to the context object as parameters, while States are created by the context object itself.
Strategies only handle a single, specific task, while States provide the underlying implementation for everything (or most everything) the context object does.

Code example description :

The treatment is given to patient based on the their state. For example providing one remdy lets say supplying oxygen might help unstable patient, however it can cause reaction or side effect to stable patient. In the example, user can pick up different treatment and based on that state of patient might change. Feel free to download and try.

Facade Design Pattern

Download the working example demo code in java from my GIT repository –https://github.com/premaseem/designPatterns/blob/master/ZipDownloadableProjects/FacadePattern.zip

To see code visit diff link: https://github.com/premaseem/designPatterns/commit/5deabc7d34da8f15c2f2e84fd9dd6c4e0978b56a

According to GoF Facade design pattern is:

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

How do we infer the above definition? Think of a component that solves a complex business problem. That component may expose lot of interfaces to interact with it. To complete a process flow we may have to interact with multiple interfaces.

To simplify that interaction process, we introduce facade layer. Facade exposes a simplified interface (in this case a single interface to perform that multi-step process) and internally it interacts with those components and gets the job done for you. It can be taken as one level of abstraction over an existing layer.

Facade design pattern is one among the other design patterns that promote loose coupling. It emphasizes one more important aspect of design which is abstraction. By hiding the complexity behind it and exposing a simple interface it achieves abstraction.

Real World Examples for Facade Pattern

I wish to give you couple of real world examples. Lets take a car, starting a car involves multiple steps. Imagine how it would be if you had to adjust n number of valves and controllers. The facade you have got is just a key hole. On turn of a key it send instruction to multiple subsystems and executes a sequence of operation and completes the objective. All you know is a key turn which acts as a facade and simplifies your job.

Similarly consider microwave oven, it consists of components like trasnformer, capacitor, magnetron, waveguide and some more. To perform an operation these different components needs to be activated in a sequence. Every components has different outputs and inputs. Imagine you will have separate external controller for all these components using which you will heat the food. It will be complicated and cumbersome.

In this scenario, oven provides you preprogrammed switches which can be considered as a facade. On click on of a single switch the job gets done. That single menu switch works as an abstraction layer between you and the internal components.

These are realworld examples for facade design pattern. In software scenario, you can have interfaces which acts as a facade. Methods in these interfaces contains the interaction sequence, formatting and converting data for input for components. As such it will not hold the business logic.

Common Mistakes while Implementing Facade Design Pattern

In my experience the common mistakes I have seen is,

  • just for the sake of introducing a facade layer developers tend to create additional classes. Layered architecture is good but assess the need for every layer. Just naming a class as ABCDFacade.java doesn’r really make it a facade.
  • Creating a java class and ‘forcing’ the UI to interact with other layers through it and calling it a facade layer is one more popular mistake. Facade layer should not be forced and its always optional. If the client wishes to interact with components directly it should be allowed to bypass the facade layer.
  • Methods in facade layer has only one or two lines which calls the other components. If facade is going to be so simple it invalidates its purpose and clients can directly do that by themselves.
  • A controller is not a facade.
  • Facade is ‘not’ a layer that imposes security and hides important data and implementation.
  • Don’t create a facade layer in advance. If you feel that in future the subsystem is going to evolve and become complicated to defend that do not create a stub class and name it a facade. After the subsystem has become complex you can implement the facade design pattern.
  • Subsystems are not aware of facade and there should be no reference for facade in subsystems.

Summary of Facade Design Pattern

  • Facade provides a single interface.
  • Programmers comfort is a main purpose of facade.
  • Facade design pattern is used for promoting subsystem independence and portability.
  • Subsystem may be dependent with one another. In such case, facade can act as a coordinator and decouple the dependencies between the subsystems.
  • Translating data to suit the interface of a subsystem is done by the facade.

Facade Vs Mediator Design Pattern

Mediator design pattern may look very similar to facade design pattern in terms of abstraction. Mediator abstracts the functionality of the subsystems in this way it is similar to the facade pattern. In the implementation of mediator pattern, subsystem or peers components are aware of the mediator and that interact with it. In the case of facade pattern, subsystems are not aware of the existence of facade. Only facade talks to the subsystems.

Design Pattern : Adapter in Java

The adapter pattern is a structural design pattern that allows you to repurpose a class with a different interface, allowing it to be used by a system which uses different calling methods.

Adopter Design pattern

 

A square peg in a round hole

A square peg in a round hole

 

The Adapter pattern translates one interface for a class into a compatible interface. It is used when two classes could conceptually work together but cannot because of implementation details. For this example, I create a few simple classes modeling the problem of fitting a square peg into a round hole. A square peg will sometimes fit into a round hole, as illustrated in figure depending on the relative sizes of the peg and the hole:

 

 

To determine if a square will fit into a circle, I use the formula shown here



Figure 2. Formula for determining if a square will fit into a circle

I could trivially solve the square peg/round hole problem with a simple utility class that handles conversions. But it exemplifies a larger problem. For example, what if I’m adapting a Button to fit on a type of Panel that it wasn’t designed for yet can be made compatible with? The problem of square pegs and round holes is a convenience simplification of the general problem addressed by the Adapter design pattern: adapting two incompatible interfaces. To enable square pegs to work with round holes, I need a handful of classes and interfaces to implement the Adapter pattern, as shown in Listing 1:

 

Listing 1. Square pegs and round holes in Java

 

public class SquarePeg {

private int width;

 

public SquarePeg(int width) {

this.width = width;

}

 

public int getWidth() {

return width;

}

}

 

public interface Circularity {

public double getRadius();

}

 

public class RoundPeg implements Circularity {

private double radius;

 

public double getRadius() {

return radius;

}

 

public RoundPeg(int radius) {

this.radius = radius;

}

}

 

public class RoundHole {

private double radius;

 

public RoundHole(double radius) {

this.radius = radius;

}

 

public boolean pegFits(Circularity peg) {

return peg.getRadius() <= radius;

}

}

 

To reduce the amount Java code, I’ve added an interface named Circularity to indicate that the implementer has a radius. This lets me write the RoundHole code in terms of round things, not just RoundPegs. This is a common concession in the Adapter pattern to make type resolution easier.

To fit square pegs into round holes, I need an adapter that adds Circularity to SquarePegs by exposing a getRadius() method, as shown in Listing 2:
Listing 2. Square peg adapter

 

public class SquarePegAdaptor implements Circularity {

private SquarePeg peg;

 

public SquarePegAdaptor(SquarePeg peg) {

this.peg = peg;

}

 

public double getRadius() {

return Math.sqrt(Math.pow((peg.getWidth()/2), 2) * 2);

}

}

 

To test that my adapter does in fact let me fit suitably sized square pegs in round holes, I implement the test shown in Listing 3:
Listing 3. Testing adaptation

 

@Test

public void square_pegs_in_round_holes() {

RoundHole hole = new RoundHole(4.0);

Circularity peg;

for (int i = 3; i <= 10; i++) {

peg = new SquarePegAdaptor(new SquarePeg(i));

if (i < 6)

assertTrue(hole.pegFits(peg));

else

assertFalse(hole.pegFits(peg));

}

}

 

In Listing 3, for each of the proposed widths, I wrap the SquarePegAdaptor around the creation of the SquarePeg, enabling hole’s pegFits() method to return an intelligent evaluation as to the fitness of the peg.

This code is straightforward, because this is a simple albeit verbose pattern to implement in Java. This paradigm is clearly the GoF design-pattern approach. However, the pattern approach isn’t the only way.

UML