Showing posts with label Structural Design Patettern. Show all posts
Showing posts with label Structural Design Patettern. Show all posts

Wednesday, June 1, 2016

Flyweight Pattern example java

Flyweight reduces the cost of creating and manipulating a large number of similar objects.Flyweight is used when there is a need to create large number of objects which are in similar nature.Large number of objects consumes high memory and flyweight design pattern gives a solution to reduce the load on memory by sharing objects.It is achieved by isolating object properties into two types intrinsic and extrinsic .

Intrinsic and Extrinsic State:

Create only 25 objects for mapping every unique characters. these 26 objects will have intrinsic state as its character.that is object '"a" will have state as character "a" .then what happens to color ,font and size? those are the extrinsic state and will be passed by client code.26 objects will be in store;client code will get the needed character/object and pass the extrinsic state to it with respect to the context.with respect to context means '''a" in first line may com in red color and same character may com in blue in different line.

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 attribute can be made external and shared.
  • Its better when extrinsic state can be computed rather than stored.

Proxy Design Pattern in java tutorial

What is Proxy Design Pattern?

First of all its a structural pattern and Proxy means in place of.In our collage times we gave proxy in place of or on behalf of are literal meanings of proxy.There are many different flavors of proxy depending on its purpose.we may have a protection proxy to control access rights to an object.

For Example:

Let say you want to attach  an image with an e-mail .now suppose this email has to be sent to millions of consumers in an e-mail campaign.Attaching the image and sending along with the e-mail will be very heavy operation.

So what we can do instead send the image as a link to one of the servlet. The Place Holder of the image will be sent.Once the email reaches the consumer the image place holder will call the servlet and load the image at run time from server.

Now when to use Proxy Pattern:

It is used when we need to represent a complex object with a simpler one.If creation of object is expensive,its creation can be suspended till the necessity arises  and till then a simple object can represent it.The Simple Object is called the Proxy for the complex Object.

Implementation:

/**
 * @author Abhinaw.Tripathi
 *
 */

interface Image
{
 public void showImage();
}

class RealImage implements Image
{
public RealImage(URL url)
{
loadImage(url);
}
private void loadImage(URL url)
{
// operation to load image
}
@Override
public void showImage()
{
// TODO Auto-generated method stub
//display the image

}
}

class ProxyImage implements Image
{

private URL url;
public ProxyImage(URL url) {
this.url=url;
}


public ProxyImage(String string) {
// TODO Auto-generated constructor stub
}


@Override
public void showImage() {
// TODO Auto-generated method stub
RealImage real=new RealImage(url);
real.showImage();
}
 
}

public class ProxyPatternTest {

/**
*
*/
public ProxyPatternTest() {
// TODO Auto-generated constructor stub
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

     Image img1=new ProxyImage("testfolder/image1.png");
     Image img2=new ProxyImage("testfolder/image2.png");
     img1.showImage();  // you can do something like this.
}

}

Tuesday, May 31, 2016

Facade Design Pattern tutorial in java

What is Facade Design Pattern?

Facade is a structural Design Pattern and In java the interface JDBC is an example of facade pattern.we as a user creates connection using the java.sql.connection interface,the implementation of which we are not concerned about.

Let us consider a simple example for understanding the pattern.while walking past the road we can only see this glass face of the building.we do not know anything about it,the wiring,the pipes and other complexities.
The face hides all the complexity of the building and displays a good looking front.

Facade design is one among the other design patterns that promotes loose coupling.

Implementation:

/**
 * @author Abhinaw.Tripathi
 *
 */

class GUIMenu
{
  public void drawMenuButton()
  {  
  }
}
class GUITitleBar
{
  public void showTitleBar(String caption)
  {  
  }
}

class GUIContent
{
  public void showButton()
  {  
  }

  public void showtextFeilds()
  {

  }

  public void setDefaultsValues()
  {

  }
}


class MyGUI
{
 private GUIMenu menu;
 private GUITitleBar titleBar;
 private GUIContent content;

 public MyGUI() {
// TODO Auto-generated constructor stub
menu=new GUIMenu();
titleBar=new GUITitleBar();
content=new GUIContent();
}

 public void drawGUI()
 {

content.showButton();
content.setDefaultsValues();
content.showtextFeilds();
menu.drawMenuButton();
titleBar.showTitleBar("Title of the GUI");
 }


}

public class FacadeDesignTest {

/**
*
*/
public FacadeDesignTest() {
// TODO Auto-generated constructor stub
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyGUI facade=new MyGUI();
facade.drawGUI();

}


}

When to Use Facade Design Pattern:
  • you want to provide a simple interface to a complex subsystem.
  • there are many dependencies between clients and the implementation classes of an abstraction.
  • you want to layer your subsystems.Use a facade to define an entry point to each subsystem level.
  • Facade provides a single interface.

Decorator Pattern implementation in java tutorial or example

What is Decorator Patter?

It changes(extends or modify) the behavior of an instance at run time.

When to use Decorator Pattern:

We can choose any single object of a class and modify its behaviour leaving the other instances unmodified.Inheritance adds functionality to classes whereas the decorator pattern adds functionality to objects in other objects.

Implementation:

/**
 * @author Abhinaw.Tripathi
 *
 */
interface House
{
  public String makeHouse();
}

class SimpleHouse implements House
{

@Override
public String makeHouse() {
// TODO Auto-generated method stub
return "Base House";
}

}

abstract class HouseDecorator implements House
{
protected House house;

public HouseDecorator(House h)
{
this.house=h;
}
public String makeHouse()
{
return house.makeHouse();
}
}

class ColorDecorator extends HouseDecorator
{

public ColorDecorator(House h) {
super(h);
// TODO Auto-generated constructor stub
}

private String addColors()
{

return "+colors";
}
public String makeHouse()
{
return house.makeHouse() + addColors() ;
}

}

public class DecoratorPatternTest {

/**
*
*/
public DecoratorPatternTest() {
// TODO Auto-generated constructor stub
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

House house =new ColorDecorator(new ColorDecorator(new SimpleHouse())) ;
System.out.println(house.makeHouse());
}


}



Design Pattern Composite Design Pattern tutorial example java

What is Composite Design Pattern?

A composite pattern is a collection of objects and they may be either a composite or just a primitive object.such as programmers develop systems in which a component may be an individual object or it may represent a collection of objects.
The composite pattern allows  us to build complex objects by recursively composing similar objects in a tree-like manner.

When to use Composite Design Pattern:


  • Manipulating  a single object should be as similar to manipulating a group of objects.
  • Recursive formation and tree structure for composition should be noted.

Implementation:

import java.util.ArrayList;
import java.util.List;

/**
 *
 */

/**
 * @author Abhinaw.Tripathi
 *
 */

interface FileComponent
{
  public void printName();
}

class LeafFile implements FileComponent
{
  private String fileName;
public LeafFile(String name)
{
this.fileName=name;
}

@Override
public void printName() {
// TODO Auto-generated method stub
System.out.println("File Name:" +fileName);
}

}

class Directory implements FileComponent
{
private String fileName;
private List files=new ArrayList<>();

public Directory(String name) {
this.fileName=name;
}

void add(FileComponent obj)
{
files.add(obj);
}

@Override
public void printName() {
// TODO Auto-generated method stub
System.out.println("Directory Name :" + fileName);
for(int i=0;i<files.size();++i)
{
FileComponent obj=(FileComponent)files.get(i);
obj.printName();
}
}

}

public class CompositeDesignTest {

/**
*
*/
public CompositeDesignTest() {
// TODO Auto-generated constructor stub
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

Directory one =new Directory("test123"),
two=new Directory("test456"),
three=new Directory("test789");

LeafFile a=new LeafFile("a.txt"),
b=new LeafFile("b.txt"),
c=new LeafFile("c.txt"),
d=new LeafFile("d.txt"),
e=new LeafFile("e.txt");

one.add(a);
one.add(two);
one.add(b);
two.add(c);
two.add(d);
two.add(three);
three.add(e);
one.printName();

}

}

Design Pattern - Bridge Design Pattern java

What is Bridge Design Pattern?

Bridge DP is Structural Pattern.Bridge pattern is used to separate out the interface from its implementation.

For Example:   Let us take case of Electrical equipments we have at home and their switches.Switch of the fan.the switch is the interface and the actual implementation is the running of the fan once its switched-on .both the switch and fan  are independent of each other.

Implementation:

/**
 * @author Abhinaw.Tripathi
 *
 */
interface Tv
{
  public void powerOn();
  public void powerOff();
  public void channelChange(int channel);
}

class Google implements Tv
{

@Override
public void powerOn() {
// TODO Auto-generated method stub
//google specific code
}

@Override
public void powerOff() {
// TODO Auto-generated method stub
//google specific code
}

@Override
public void channelChange(int channel) {
// TODO Auto-generated method stub
//google specific code
}
}

class Samsung implements Tv
{

@Override
public void powerOn() {
// TODO Auto-generated method stub
//Samsung specific code
}

@Override
public void powerOff() {
// TODO Auto-generated method stub
//Samsung specific code
}

@Override
public void channelChange(int channel) {
// TODO Auto-generated method stub
//Samsung specific code
}
}

abstract class TVremoteControl
{
  private Tv implementor;
  
  public void powerOn()
  {
 implementor.powerOn();
  }
  
  public void powerOff()
  {
 
 implementor.powerOff();
  }
  
  public void setChannel(int channnel)
  {
 implementor.channelChange(channnel);
 
  }
  
}

class ConcreteTVRemoteControl extends TVremoteControl
{
private int currentChannel;
public void nextChannel()
{
currentChannel++;
setChannel(currentChannel);
}
public void prevChannel()
{
currentChannel --;
setChannel(currentChannel);
}
}



public class BridgePatternTest {

/**
* 
*/
public BridgePatternTest() {
// TODO Auto-generated constructor stub
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ConcreteTVRemoteControl remote=new ConcreteTVRemoteControl();
remote.nextChannel();
remote.setChannel(12);
remote.prevChannel();
remote.powerOff();
remote.powerOn();
remote.powerOff();

}

}

When to Use Bridge Design Pattern:

1) This pattern should be used when both  the class as well  as what it does very often.
2)It can also be thought of as two layer  of abstraction.
3)It is useful in times when you need to switch between multiple implementations at runtime.

Thursday, May 26, 2016

Structural Design Pattern tutorial example java

What is Structural Design Pattern?

Ans: 

Structural DP,s are used for structuring code and objects.It also can be described as how objects and classes can be combined to form larger structures.
Structural design patterns are used to organize our program into groups.

Categories of Structural Design Patterns


  • Object-Structural Design Pattern- It deals with how objects can be associated and composed to form larger and more complex structures.
  • Class-Structural Design Pattern - It deals with with abstraction using inheritance and provide more useful program interface.
Structural Design Patterns:
  • Adapter Pattern( is Class Structural Pattern only and rest all object.)
  • Bridge Pattern
  • Composite Pattern
  • Decorator Pattern
  • Facade Pattern
  • Flyweight Pattern
  • Proxy Pattern