Tuesday, May 31, 2016

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();

}

}

No comments: