Loading...

Follow My experience in Java on Feedspot

Continue with Google
Continue with Facebook
or

Valid

Building Design Pattern is one of the Creational Design Patterns. In this design pattern we create small parts of an object and then we arrange them as per requirement to create the final object.

For example, you are a car builder. You can manufacture car’s Tyre, then it’s engine, then body, then interior and finally you can arrange all of these parts of a car to build a complete car. Also you can make sure that while arranging parts of a car, it must have wheels else you will not build it. That means, there is a pretty much good scope for validations as well.

So in short, builder design pattern focuses on creating small parts of an object and then arranging them to create a final complete object. That means, you can create a part of an object as and when required where it is not mandatory that you should supply all the information at once. You can break the object into multiple parts and can create them wherever required. And in the end, you can validate all the parts and can arrange them to create a final object.

Let’s have a look at the following application where we shall see that how we are using CarBuilder to build a Car.

Eclipse Project Folder Structure
MainClass.java

You can see that in MainClass, we asked for an instance of CarBuilder and then used this instance to set multiple attributes of a car. In the end, we invoke a build() method who arranges all the attributes of a car and check if car object can be built or not and accordingly throw an exception or return an object of Car with all the attributes that you provided using CarBuilder.

package designpattern.builder;

public class MainClass {

	public static void main(String[] args) {
		CarBuilder carBuilder = CarBuilder.getCarBuilder();
		try {
			Car car = carBuilder.setBrand("Maruti").setColor("Grey").setCost(8.75f).setModel(2019).setName("Baleno")
					.setTransmission(CarBuilder.Transmission.Manual).build();
			car.displayCarInformation();
		} catch (Exception exception) {
			System.err.println(exception.getMessage());
		}
	}
}
Car.java
package designpattern.builder;

import designpattern.builder.CarBuilder.Transmission;

public class Car {
	private String brand;
	private String name;
	private int model;
	private String color;
	private Transmission transmission;
	private float cost;

	public Car(String brand, String name, int model, String color, Transmission transmission, float cost) {
		super();
		this.brand = brand;
		this.name = name;
		this.model = model;
		this.color = color;
		this.transmission = transmission;
		this.cost = cost;
	}

	public void displayCarInformation() {
		System.out.println("Car Information:");
		System.out.println("Brand - " + brand);
		System.out.println("Name - " + name);
		System.out.println("Model - " + model);
		System.out.println("Color - " + color);
		System.out.println("Transmission - " + transmission);
		System.out.println("Cost - " + cost);
	}
}
CarBuilder.java

The beauty of Builder is that for all the setters you’ll return the instance of builder itself which creates a chain of setter for you. That means, one can set multiple attributes of a car in one line as shown below:

package designpattern.builder;

public class CarBuilder {
	private String brand;
	private String name;
	private int model;
	private String color;
	private Transmission transmission;
	private float cost;
	
	enum Transmission {
		Manual, Automatic
	}
	
	private CarBuilder() {
		// To restrict object creation from the outside world
	}
	
	public static CarBuilder getCarBuilder() {
		return new CarBuilder();
	}
	
	public CarBuilder setBrand(String brand) {
		this.brand = brand;
		return this;
	}
	
	public CarBuilder setName(String name) {
		this.name = name;
		return this;
	}
	
	public CarBuilder setModel(int model) {
		this.model = model;
		return this;
	}
	
	public CarBuilder setColor(String color) {
		this.color = color;
		return this;
	}
	
	public CarBuilder setTransmission(Transmission transmission) {
		this.transmission = transmission;
		return this;
	}
	
	public CarBuilder setCost(float cost) {
		this.cost = cost;
		return this;
	}
	
	public Car build() throws Exception {
		// Add restrictions in the build() method as required
		if(brand == null || brand.trim().length() == 0) {
			throw new Exception("Brand value is mandatory");
		}
		return new Car(brand, name, model, color, transmission, cost);
	}
}

For any queries, kindly comment below as I would love to address all of them.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Facade Design Pattern is one of the Structural Design Patterns.

Facade Design Pattern says that the concept of Facade is similar to a building’s face. When you look at a building you find it beautiful and easy to use (whether it is for living or any other commercial stuffs you want to do with it). But you aren’t aware of it’s wiring, plumbing and other internal complexities. And even I think that one should not care about those stuffs as your focus is either staying there or doing some other tasks within the building.

That is what Facade Design Pattern says. It says that client should not be aware of the complexity of the API that they are using. So Facade Design Pattern helps us in designing the API in such a way that it is easy for third party users to consume irrespective of knowing that how complex is the logic inside.

Let’s have a look at the following implementation and then we’ll talk about it even more. Try to understand the code before I explain it. Just an exercise for you to get some confidence over what you’ve learnt so far.

Project Explorer Snippet

Code Explanation

As one can see that in MainClass.java, we are using DisplayFacade and we just pass-on the parameter. We are not sure how complex is the internal logic to display content on either TV or Mobile. However, I have used very simple program so that one can understand the concept but just imagine a situation where DisplayFacade‘s display method is having a complex logic (around 500 lines of code)? Then look at the invocation for DisplayFacade‘s display method which seems quite simple to use but API user is not aware of its complexity. In same way, Facade can have plethora of methods and large number of method parameters so that API user can avail it’s power without understanding the internal logic.
MainClass.java
package facadedesignpattern;

public class MainClass {

	public static void main(String[] args) {
		DisplayFacade displayFacade = new DisplayFacade();
		displayFacade.display("tv");
		System.out.println("========================");
		displayFacade.display("mobile");
	}

}
DisplayFacade.java
package facadedesignpattern;

public class DisplayFacade {

	private Mobile mobile;
	private Television tv;

	DisplayFacade() {
		mobile = new Mobile();
		tv = new Television();
	}

	public void display(String target) {
		switch (target.toLowerCase()) {
		case "tv":
			tv.display();
			break;
		case "mobile":
			mobile.display();
			break;
		}
	}

}
Display.java
package facadedesignpattern;

public interface Display {
	void display();
}
Mobile.java
package facadedesignpattern;

public class Mobile implements Display {

	@Override
	public void display() {
		System.out.println("Displaying on Mobile");
	}

}
Television.java
package facadedesignpattern;

public class Television implements Display {

	@Override
	public void display() {
		System.out.println("Displaying on Television");
	}

}

Like / Comment / Share / Subscribe and help us in building a simple programming community for users who struggle with complex books and tutorials.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Hello Everyone,

Here I came with another post. Thank you all for your support and encouragement.

So in this post, we’ll talk about converting XML into Strong Types or we can say classes and objects. We’ll also try to find out that why we should do it and where we can use it.

Why we should using XML to Strong Type conversion and where?

To understand the answer of why and where, let’s take an example of a small application where you take input from user on GUI or on console and after pressing Enter or clicking OK button it’ll generates a text file containing all the textual information that you’ve authored/input.

Now suppose you want to save that file with name MyContent.txt some where in your PC. If you just want to develop a simple application then probably you’ll hardcode the output file name MyContent.txt in your code. Now, what if i’ll ask you to save the file with MyText.txt? You have to change that file name string in your code and recompile it. Right?

These kind of changes should be configurable which is the first answer that why we use XML in our applications.

Suppose you have written a very simple configuration xml as shown below:

<filename file-extension=".txt">MyContent</filename>

So now your application will pick the output filename from the xml mentioned above which will make your application configurable. So you don’t need to change your code. All you need to do is make a change in XML and run the application. That’s it.!

Now let’s talk about conversion of XML to Strong Types. Well the custom configuration xml mentioned above is quite small. What if your application needs lot of information that should be configurable through xml? Then loading XML file from Disk, parsing the XML node to get the information is quite a heavy task. So it is always suggested to convert XML to Classes and Objects so that you can get the information from these converted classes and objects instead of loading the xml and parsing it.  Let’s update the custom configuration xml mentioned above and then we’ll see that how we can convert that xml into classes and objects.

<config>
	<output-config append="true">
		<output-file-path>C:/Users/sdass/Desktop/</output-file-path>
		<output-file-name>file.txt</output-file-name>
	</output-config>
</config>

The very basic thing that you need to keep in mind is that, each node represents a class. For example, configoutput-config, output-file-path, output-file-name  will be classes whereas the attribute of a node will be converted into the property of that class.

Let’s have a look at the small application below.

Eclipse Project Snippet

In MainClass.java, you would find that a config.xml is being loaded from the classpath. Then I have used the JAXB API provided by Java itself.

This application is developed using Java 8.

JAXB API’s method that I have used takes two arguments. First, xml file which needs to be unmarshalled (or we can say converting xml to strong types) and Second, the root node’s class. In our case, root node is <config> and as I have already mentioned above that there will be a separate class from each xml node which contains complex content (in other words a xml or non-primitive data). That’s why the second parameter to the unmarshal method is the class of the root node. Rest of the code is pretty simple where I have added “Sandeep Dass” as a content to the file.

The main area of focus is how to let know the JAXB API that you have to map this xml node with this class. Well it is pretty simple. You can refer to the Config.java and OutputConfig.java. Just create a simple public (so that it is accessible to JAXB) java class and use different annotations to define behavior of each class and it’s data members.

MainClass.java
package classes;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.bind.JAXB;

public class MainClass {

	public static void main(String[] args) {
		InputStream inputStream = MainClass.class.getResourceAsStream("/configuration/config.xml");
		Config config = JAXB.unmarshal(inputStream, Config.class);
		File outputFile = new File(config.outputConfig.outputFilePath + config.outputConfig.outputFileName);
		FileOutputStream fileOutputStream = null;
		try {
			fileOutputStream = new FileOutputStream(outputFile, config.outputConfig.append);
			fileOutputStream.write("Sandeep Dass".getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally {
			if(fileOutputStream != null) {
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
Config.java
package classes;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "config")
public class Config {
	
	@XmlElement(name = "output-config")
	public OutputConfig outputConfig;
}
OutputConfig.java
package classes;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;

public class OutputConfig {
	@XmlAttribute(name="append")
	public boolean append;
	
	@XmlElement(name = "output-file-path")
	public String outputFilePath;
	
	@XmlElement(name = "output-file-name")
	public String outputFileName;
}

Kindly share your feedback/queries in the comment section below.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Separate tags by commas
To access this feature, please upgrade your account.
Start your free month
Free Preview