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

Coffee break #124. Builder design pattern. How serialization and deserialization works 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 works 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 the problems that the Factory and Abstract Factory design patterns had when a class object contains many field values ​​and/or data. Before we move on to the Builder pattern , let's see what exactly the problems are 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 lead to errors because in most cases the type of the arguments is the same and it is difficult for the client to maintain the order of the arguments.

  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 complex to 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 just need to provide the constructor with the necessary parameters, and then various setter methods to set the optional parameters. Note that the problem with this method is that the object's state will remain inconsistent if all attributes are not clearly set.

What is the Builder Design Pattern?

The Builder pattern solves the problem with lots of optional parameters and inconsistent states by providing a way to incrementally create an object. For this, a method is used that actually returns the final object.

How to implement the Builder design pattern in Java?

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

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

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

  4. The final step is to provide a build() method on the Builder class that 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 idea 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();
    }
}
Builder pattern example : java.lang.StringBuilder and java.lang.StringBuffer used the Builder pattern to build objects.

How serialization and deserialization works in Java

Source: Medium I switched to Java in January of this year after an internship. Before that, I mostly wrote in PHP and a little bit in JavaScript. I've never dealt with serialization before, although serialization actually exists in PHP as well. True, in Java it is used much more often. Today I'll walk you through how serialization and deserialization work in Java and show you 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, then this process is called deserialization.

Serialization and Deserialization Example

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, an id and a name, which are changed from their default value when the class is instantiated. The Serializable interface and other classes used in the program have been 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 the 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 opposite of serialization. To restore an object from a sequence of bytes, use the ObjectInputStream and the readObject method . Note that in order to access the fields in the Person class, the object is cast to the Person data type.. An object of a class that does not implement a serialization interface cannot be serialized. Therefore, any class that refers to a class that implements the serialization interface must itself implement the serialization interface or an exception will be thrown. Serialization is platform independent, that is, a serializable stream of bytes can be deserialized by another JVM. 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 the case of a static field, it is not serialized because the static field belongs to the class, not the 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 configured. This is called custom serialization.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION