Showing posts with label DESIGN PATTERN - STRUCTURAL. Show all posts
Showing posts with label DESIGN PATTERN - STRUCTURAL. Show all posts

Tuesday, April 18, 2017

Composite Design Pattern in Java

INTRODUCTION

  • The Composite Design pattern is categorized under Structural Patterns.
  • It helps to traverse the Tree Structured object and perform the operations on it. In the tree structure, a node which contains no child called Leaf Object and a node which contains at least one child called Composite Object.
  • The client will treat both composite object and simple object as same. Example, double clicking the folder and file will be same but the operation performed in different Objects.
  • In this pattern, accessing of an object’s behavior follows the recursion principle if it contains multiple children.

EXAMPLE

Following are the examples from Java API.
  1. add(Component comp) method of java.awt.Container class.
  2. In Collection Framework
    1. addAll(Collection<? extends E> c) method of java.util.List interface.
    2. addAll(Collection<? extends E> c) method of java.util.Set interface.
    3. putAll(Map<? extends K,? extends V> m) method of java.util.Map interface.

WHEN TO USE?

The composite design pattern can be used when
  1. You want to handle the part-whole hierarchies of the object, i.e an objects which may have children or without children (tree-structured objects). part denotes the individual object and whole denotes the composite object.
  2. If the client didn’t want to know the difference between the composite object and simple object.

USECASE

Assembling the car. A Car will consist multiple components and those components may be an individual component or again it may be assembled with multiple individual components.
Car assembling may have below processes.
  1. Assembling Engine
  2. Assembling Body - It may have sub-processes like
  1. Assembling Front Body
  2. Assembling Center Body
  3. Assembling Back Body
  1. Assembling Wheel - It may have sub-processes like
  1. Assembling Tyre
  2. Assembling Chassis
Below the tree representation of whole assembling process.
Leaf Objects - Engine, Front, Center, Back, Tyre and Chassis
Composite Objects - Car, Body, and Wheel

ENTITIES

Composite Design pattern contains the following entities.
  1. Component - It is an interface consist of all the functionality of the both composite and simple objects.
  2. Composite - Composite represents an object which should have at least one child object. It also performs the child operations so that when a composite object is accessed, it also gives the result of all it’s children.
  3. Leaf - Leaf represents an object which has zero children.
  4. Client - who will access the Component and manipulates the Composite object or individual object

IMPLEMENTATION

Define Component

First, create an interface(CarComponent.java)which represents the Component Object.
public interface CarComponent {
 String getName();

 long getPrice();

 void assembly();

 void addComponent(CarComponent component);

 void removeComponent(CarComponent component);
}

Implement the Leaf Object

A Leaf object is the one has no children for it. So create a class (Engine.java) which will implement all the components behaviors.
public class Engine implements CarComponent {

 @Override
 public String getName() {
   return "Engine";
 }

 @Override
 public long getPrice() {
   return 50000;
 }

 @Override
 public void assembly() {
   System.out.println("Engine - Assembly DONE");
 }

 @Override
 public void addComponent(CarComponent component) {
   // no components to add
 }

 @Override
 public void removeComponent(CarComponent component) {
   // no components to remove
 }

}

Implement the Composite Object

In the above example, the assembling of wheel contains the subprocess, so create another class (Wheel.java) which represents the Composite object and also has the child operations.
import java.util.ArrayList;
import java.util.List;

public class Wheel implements CarComponent {

 private List<CarComponent> wheelComponents = new ArrayList<>();

 public Wheel() {
   this.addComponent(new Tyre());
   this.addComponent(new Chassis());
 }

 @Override
 public String getName() {
   return "Wheel";
 }

 @Override
 public long getPrice() {
   long price = 0;

   for (CarComponent component : wheelComponents) {
     System.out.println(component.getName() + " Price " + component.getPrice());
     price = price + component.getPrice();
   }

   return price;
 }

 @Override
 public void assembly() {
   for (CarComponent component : wheelComponents) {
     component.assembly();
     System.out.println(component.getName() + " - Assembly DONE");
   }

   System.out.println("Wheel - Assembly DONE");
 }

 @Override
 public void addComponent(CarComponent component) {
   this.wheelComponents.add(component);
 }

 @Override
 public void removeComponent(CarComponent component) {
   // no components to remove
 }

}

Here, getPrice() & assembly() methods contains the child operations. So it produces the final result of all the children operations.

Now, implement the children objects, child 1 (Tyre.java) & child 2 (Chassis.java) has no children.
public class Tyre implements CarComponent {

 @Override
 public String getName() {
   return "Tyre";
 }

 @Override
 public long getPrice() {
   return 20000;
 }

 @Override
 public void assembly() {
   // no assembly operation here
 }

 @Override
 public void addComponent(CarComponent component) {
   // no components to add
 }

 @Override
 public void removeComponent(CarComponent component) {
   // no components to remove
 }

}

Now create a Client(CompositePatternClient.java) which will access the Component and also performs the operations on either Composite Object or Individual Object.
public class CompositePatternClient {

 public static void main(String[] args) {
   Engine engine = new Engine();
   Wheel wheel = new Wheel();

   System.out.println("...Car Assembly...");
   engine.assembly();
   wheel.assembly();

   System.out.println("\n...Car Price...");
   long enginePrice = engine.getPrice();
   long wheelPrice = wheel.getPrice();
   System.out.println("Wheel Price(Tyre + Chassis): " + wheelPrice);
   System.out.println("Engine Price: " + enginePrice);
   System.out.println("Total Price: " + (enginePrice + wheelPrice));
 }
}

OUTPUT


...Car Assembly...
Engine - Assembly DONE
Tyre - Assembly DONE
Chassis - Assembly DONE
Wheel - Assembly DONE

...Car Price...
Tyre Price 20000
Chassis Price 30000
Wheel Price(Tyre + Chassis): 50000
Engine Price: 50000
Total Price: 100000
Hope this example clarifies the Composite Design Pattern. Please share your comments and suggestions below.
Happy Knowledge Sharing!!!

Wednesday, July 9, 2014

Facade Design Pattern

INTRODUCTION

In real life, we always look for an easy way to do our job by finding someone who can take care of our work.

USECASE

Applying for PASSPORT in India. We look for any agency instead we directly go the concerned office and apply with our details.

And we also what are all the process has been carried out and how they can perform to validate our person details to give the passport. Simply we are submitting the details and look for the delivery of the Passport hard-copy to our address.

The passport office does all the verification process for us and finally approves our passport by some verification.

Here the verification process is acting as an Interface, between me & passport office, which accepts my details and finally returns the result (Passport) what I have required.
Very importantly, the Person will not aware of the back-end process.

IMPLEMENTATION

Lets us create Model Class - Person.
public class Person {

 private String name;
 private String address;
 private String phone;
 private String dob;

 public String getDob() {
   return dob;
 }

 public void setDob(String dob) {
   this.dob = dob;
 }

 public String getName() {
   return name;
 }

 public void setName(String name) {
   this.name = name;
 }

 public String getAddress() {
   return address;
 }

 public void setAddress(String address) {
   this.address = address;
 }

 public String getPhone() {
   return phone;
 }

 public void setPhone(String phone) {
   this.phone = phone;
 }
}


Create an interface for the background verification process.

public interface Verification {
 boolean verify(String personDetail);
}

Now verify the person’s phone number.

public class PhoneNumberVerification implements Verification {
 @Override
 public boolean verify(String phone) {
   return true;
 }
}

Verify the address.

public class AddressVerification implements Verification {
 @Override
 public boolean verify(String address) {
   return true;
 }
}

Verify the Date of Birth Certificate.

public class DateOfBirthVerification implements Verification {
 @Override
 public boolean verify(String personDetail) {
   return true;
 }
}


Check whether the person involved in any criminal activity by checking with concerned police station to check about any case filed on him.

public class PoliceCaseVerification implements Verification {
 @Override
 public boolean verify(String personDetail) {    
   return true;
 }
}

Now the passport has to verify all the details one by one and finally approve or disapprove the passport.

public class PassportProcess {

 public static boolean verify(Person person) {
   Verification phoneNumber = new PhoneNumberVerification();
   Verification address = new AddressVerification();
   Verification dob = new DateOfBirthVerification();
   Verification policeCase = new PoliceCaseVerification();

   return phoneNumber.verify(person.getPhone())
       && address.verify(person.getAddress())
       && dob.verify(person.getDob())
       && policeCase.verify(person.getName());
 }
}

Now time to test the facade pattern.

public class PassportOffice {

 public static void main(String[] args) {

   // Person Details
   Person person = new Person();
   person.setName("Ranjith");
   person.setAddress("#5, Gandhi Street, T.Nagar, Chennai");
   person.setPhone("9898989898");

   // Validate the person by calling the facade.
   System.out.println(PassportProcess.verify(person) ? "Passport Approved" : "Passport Rejected");
 }
}

OUTPUT


Passport Approved

Hope this example clarifies the Facade Design Pattern. Please share your thoughts in the comment box.
Happy Knowledge Sharing!!!

Adapter Design Pattern

INTRODUCTION

When we enter into a new country and we don't know the language which they speak, it is very tough to get the things done there, so we will look for any mediator or the communicator who can understand both our language and their language.
The communicator or the mediator also called as Adapter who makes our life easier. In the programming way, the Adapter helps the caller to get the things done from the callee when both are different in nature.
So basically, the Adapter design pattern may come into picture when two or more unrelated interface should work together in an application.

USECASE

Consider I have an old application which will read the .txt & .pdf file format alone and it won't accept other file formats. My calling code sends the file and reads the content of the file.

IMPLEMENTATION

Lets us create a FileReader Interface which will have necessary methods to read a file and get the content.

public interface FileReader {  
 void readFile(String fileType);  
}

Write the implementation for the above interface.

public class MyFileReader implements FileReader {

 public void readFile(String fileType) {
   System.out.println("File Type is: "+ fileType);

   if (fileType.equalsIgnoreCase(".txt")
       || fileType.equalsIgnoreCase(".pdf")){
     System.out.println("Reading the file format : " + fileType);
   } else {
     System.out.println("ERROR..Invalid File Format, Couldn't Read!!!");
   }
 }
}

When we call MyFileReader and pass the input .txt and .docx, we will get the output as below.

Create a client.
public class AdapterPatternTest {
 public static void main(String[] args) {

   FileReader fileReader = new MyFileReader();
   fileReader.readFile(".txt");

   System.out.println("\n");
   fileReader.readFile(".pdf");

   System.out.println("\n");
   fileReader.readFile(".docx");
 }
}

OUTPUT


File Type is: .txt
Reading the file format : .txt


File Type is: .pdf
Reading the file format : .pdf


File Type is: .docx
ERROR..Invalid File Format, Couldn't Read!!!

Now we have got new requirements to read the other format like .docx, .xlsx and I don't want to change my calling code.

No need to worry here, we have got Adapter design pattern.
Adapter design pattern can be implemented in two ways.
1. Using Inheritance
2. Using Composition

IMPLEMENTATION - USING INHERITANCE

The below Adapter can help to read the .docx,.xslx format files without changing the calling code with the help of AdvancedFileReader.

Create an advanced file reader which will accept new file formats and provides output.

public class AdvancedFileReader {

 public void readFileAdvanced(String fileType) {
   if (fileType.equalsIgnoreCase(".docx") || fileType.equalsIgnoreCase(".xlsx")) {
     System.out.println("Success!! Reading advanced file format: " + fileType);
   } else {
     System.out.println("Fail!! Couldn't able to read by Advanced FileReader!!!");
   }
 }
}

Create an adapter which will accept the new file formats and calls the advanced file reader and returns the output. To achieve inheritance I am extending AdvancedFileReader here.

public class FileReaderAdapter extends AdvancedFileReader {

 public void readFile(String fileType) {
   readFileAdvanced(fileType);
 }
}

Modify the MyFileReader so that I will call the adapter for the other file formats.

public class MyFileReader implements FileReader {
 FileReaderAdapter fileReaderAdapter = new FileReaderAdapter();

 public void readFile(String fileType) {
   System.out.println("File Type is: " + fileType);

   if (fileType.equalsIgnoreCase(".txt") || fileType.equalsIgnoreCase(".pdf")) {
     System.out.println("Success!! Reading the file format : " + fileType);
   } else {
     fileReaderAdapter.readFile(fileType);
   }
 }
}

Now time to test the Adapter Design Pattern. Call the MyFileReader with new file formats and check the output.

public class AdapterPatternTest {
 public static void main(String[] args) {

   System.out.println("ADAPTER DESIGN PATTERN - INHERITANCE");
   FileReader fileReader = new MyFileReader();
   fileReader.readFile(".txt");

   System.out.println("\n");
   fileReader.readFile(".pdf");

   System.out.println("\n");
   fileReader.readFile(".docx");

   System.out.println("\n");
   fileReader.readFile(".xlsx");

   System.out.println("\n");
   fileReader.readFile(".aaa");

 }
}

OUTPUT


ADAPTER DESIGN PATTERN - INHERITANCE
File Type is: .txt
Success!! Reading the file format : .txt


File Type is: .pdf
Success!! Reading the file format : .pdf


File Type is: .docx
Success!! Reading advanced file format: .docx


File Type is: .xlsx
Success!! Reading advanced file format: .xlsx


File Type is: .aaa
Fail!! Couldn't able to read by Advanced FileReader!!!

IMPLEMENTATION - USING COMPOSITION

In FileReaderAdapter, instead of extending the AdvancedFileReader, create an instance for AdvancedFileReader and all the respective method to read advanced file formats.

public class FileReaderAdapter {

 AdvancedFileReader advancedFileReader = null;

 public void readFile(String fileType) {
   advancedFileReader = new AdvancedFileReader();

   advancedFileReader.readFileAdvanced(fileType);
 }
}

The output should be same. Checkout the Complete Source Code here.

Hope this example clarifies the Adapter Design Pattern. Please share your thoughts in the comment box.
Happy Knowledge Sharing!!!