JavaRush /Java Blog /Random EN /Coffee break #124. Builder design pattern. How Serializat...

Coffee break #124. Builder design pattern. How Serialization and Deserialization Work in Java

Published in the Random EN group

Builder design pattern in Java

Source: Medium In this article, we will learn how to design and create objects for a class using the Builder design pattern . Coffee break #124.  Builder design pattern.  How Serialization and Deserialization Work in Java - 1

Why do we need the Builder design pattern?

The Builder pattern is designed to create objects using a nested public static class that has the same data fields as the outer class. The Builder pattern was created to solve problems that were present in the Factory and Abstract Factory design patterns when a class object contains many field values ​​and/or data. Before we move on to the Builder pattern , let's look at exactly what problems arise with the Factory and Abstract Factory patterns for scenarios where an object has many field values:
  1. Having too many arguments to pass from the client program to the Factory class can cause errors because most of the time the argument type is the same and it is difficult to maintain the order of the arguments on the client side.

  2. Some parameters may be optional, but in the Factory pattern we are forced to send all parameters, and optional parameters must be sent as NULL files .

  3. If the object is “heavy” and with complex design, then all these difficulties will become part of the Factory classes, which often leads to confusion.

The above problems can be solved when the object has a large number of parameters. To do this, you simply need to provide the constructor with the required parameters, and then various setter methods to set the optional parameters. Note that the problem with this method is that the state of the object will remain inconsistent unless all attributes are clearly set.

What is the Builder design pattern?

The Builder pattern solves the problem of having a lot of optional parameters and inconsistent states by providing a way to build an object step by step. This uses a method that actually returns the final object.

How to implement the Builder design pattern in Java?

If we follow the steps below, we get the step-by-step process of creating an object and retrieving it:
  1. Create a static nested class as the Builder class , and then copy all the fields from the outer class to the Builder class . We have to follow a naming convention, so if the class name is Person , then the Builder class should be called PersonBuilder .

  2. The Builder class must have a public constructor with all required fields as parameters.

  3. The Builder class must have methods to set the optional parameters, and it must return the same Builder object after setting the optional field.

  4. The last step is to provide a build() method in the Builder class , which will return the object needed by the client program. To do this we need to have a private constructor in the main class with the Builder class as an argument.

Example:

Let's look at an example to get a clear understanding of the Builder design pattern .
public class Employee {

    private String name;
    private String company;
    private boolean hasCar;//optional
    private boolean hasBike;//optional

    private Employee(EmployeeBuilder employeeBuilder) {
        name = employeeBuilder.name;
        company = employeeBuilder.company;
        hasCar = employeeBuilder.hasCar;
        hasBike = employeeBuilder.hasBike;
    }

    public String getName() {
        return name;
    }

    public String getCompany() {
        return company;
    }

    public boolean isHasCar() {
        return hasCar;
    }

    public boolean isHasBike() {
        return hasBike;
    }

    public static class EmployeeBuilder {
        private String name;
        private String company;
        private boolean hasCar;//optional
        private boolean hasBike;//optional

        //constructor for required fields
        public EmployeeBuilder(String name, String company) {
            this.name = name;
            this.company = company;
        }

        //setter methods for optional fields
        public EmployeeBuilder setHasCar(boolean hasCar) {
            this.hasCar = hasCar;
            return this;
        }

        public EmployeeBuilder setHasBike(boolean hasBike) {
            this.hasBike = hasBike;
            return this;
        }

        //Build the Employee object
        public Employee build() {
            return new Employee(this);
        }
    }
}

class TestBuilder {
    public static void main(String[] args) {
        //Building the object of Employee thru the build() method provided in EmployeeBuilder class.
        Employee employee = new Employee.EmployeeBuilder("Vikram", "ABC").setHasBike(false).setHasBike(true).build();
    }
}
Example Builder pattern : java.lang.StringBuilder and java.lang.StringBuffer used the Builder pattern to build objects.

How Serialization and Deserialization Work in Java

Source: Medium I switched to Java in January of this year after an internship. Before this, I mostly wrote in PHP and a little JavaScript. I had never encountered serialization before, although serialization actually exists in PHP. True, in Java it is used much more often. Today I will introduce you to how serialization and deserialization work in Java and several ways to use them.

What is serialization and deserialization

Serialization is the transformation of an object from a class into a sequence of bytes in the Java Virtual Machine (JVM) for transmission to another Java Virtual Machine. If the Java Virtual Machine recreates an object from bytes, the process is called deserialization.

Example of serialization and deserialization

Serialization

Let's create a class whose object will be serialized:
import java.io.*;

public class Person implements Serializable{

int id = 0;
String name = "empty";

public Person(int identity, String nomenclature) {

name = nomenclature;
id = identity;
}
}
The Person class implements Serializable so that its object can be serialized/deserialized. The Person class has two fields: identifier and name, which change from the default value when an instance of the class is created. The Serializable interface and other classes used in the program were imported into the Java.io package.
public static void main(String[] args) throws FileNotFoundException, IOException {

String filename = "filename here";
Person person = new Person(1, "John");

// serialization
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename));

try {

out.writeObject(person);
System.out.println("Success");
} catch(Exception e) {

System.out.println("Unsuccessful");
} finally {

if(out != null) {

out.close();
}
}
}
As you know, the main method starts the serialization and prints a success message, otherwise an error message is printed. To serialize objects we use ObjectOutputStream and the writeObject method .

Deserialization

public static void main(String[] args) throws FileNotFoundException, IOException {

String filename = "filename here";
Person person = new Person(1, "John");

// Deserialization
ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename));

try {

Person personObj = (Person)in.readObject();
System.out.println("Person Id is " +personObj.id + " while name is " + personObj.name);
} catch (Exception e) {

e.printStackTrace();
} finally {

if(in != null) {

in.close();
}
}
}
Deserialization is the reverse of serialization. To reconstruct an object from a sequence of bytes, use ObjectInputStream and the readObject method . Note that to provide access to fields in the Person class, the object is cast to the Person data type . A class object that does not implement the serialization interface cannot be serialized. Therefore, any class that references a class that implements a serialization interface must itself implement the serialization interface, otherwise an exception will be thrown. Serialization is platform independent, meaning the byte stream being serialized can be deserialized by another Java Virtual Machine. Static and transient fields are not serializable, so if you have a field that you don't want to serialize, make it temporary or static. In case of a static field, it is not serialized because a static field belongs to a class and not an object. Because of this, the transition state prevents the field from being serialized. Serialization is used in Hibernate, JPA and RMI. Serialization can also be customized. This is called custom serialization.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION