What is builder pattern in java

Builder

Separate the construction of a complex object from its representation so that the same construction process can create different representations.

# Explanation

Imagine a character generator for a role-playing game. The easiest option is to let the computer create the character for you. If you want to manually select the character details like profession, gender, hair color, etc. the character generation becomes a step-by-step process that completes when all the selections are ready.

Allows you to create different flavors of an object while avoiding constructor pollution. Useful when there could be several flavors of an object. Or when there are a lot of steps involved in creation of an object.

The builder pattern is an object creation software design pattern with the intentions of finding a solution to the telescoping constructor anti-pattern.

Having said that let me add a bit about what telescoping constructor anti-pattern is. At one point or the other, we have all seen a constructor like below:

public Hero(Profession profession, String name, HairType hairType, HairColor hairColor, Armor armor, Weapon weapon)  > 

As you can see the number of constructor parameters can quickly get out of hand, and it may become difficult to understand the arrangement of parameters. Plus this parameter list could keep on growing if you would want to add more options in the future. This is called telescoping constructor anti-pattern.

Programmatic Example

The sane alternative is to use the Builder pattern. First of all, we have our hero that we want to create:

public final class Hero  private final Profession profession; private final String name; private final HairType hairType; private final HairColor hairColor; private final Armor armor; private final Weapon weapon; private Hero(Builder builder)  this.profession = builder.profession; this.name = builder.name; this.hairColor = builder.hairColor; this.hairType = builder.hairType; this.weapon = builder.weapon; this.armor = builder.armor; > > 

Источник

Builder Design Pattern in Java

Builder Design Pattern in Java

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Today we will look into Builder pattern in java. Builder design pattern is a creational design pattern like Factory Pattern and Abstract Factory Pattern.

Builder Design Pattern

builder pattern in java, builder design pattern, builder pattern

Builder pattern was introduced to solve some of the problems with Factory and Abstract Factory design patterns when the Object contains a lot of attributes. There are three major issues with Factory and Abstract Factory design patterns when the Object contains a lot of attributes.

  1. Too Many arguments to pass from client program to the Factory class that can be error prone because most of the time, the type of arguments are same and from client side its hard to maintain the order of the argument.
  2. Some of the parameters might be optional but in Factory pattern, we are forced to send all the parameters and optional parameters need to send as NULL.
  3. If the object is heavy and its creation is complex, then all that complexity will be part of Factory classes that is confusing.

We can solve the issues with large number of parameters by providing a constructor with required parameters and then different setter methods to set the optional parameters. The problem with this approach is that the Object state will be inconsistent until unless all the attributes are set explicitly. Builder pattern solves the issue with large number of optional parameters and inconsistent state by providing a way to build the object step-by-step and provide a method that will actually return the final Object.

Builder Design Pattern in Java

Let’s see how we can implement builder design pattern in java.

  1. First of all you need to create a static nested class and then copy all the arguments from the outer class to the Builder class. We should follow the naming convention and if the class name is Computer then builder class should be named as ComputerBuilder .
  2. Java Builder class should have a public constructor with all the required attributes as parameters.
  3. Java Builder class should have methods to set the optional parameters and it should return the same Builder object after setting the optional attribute.
  4. The final step is to provide a build() method in the builder class that will return the Object needed by client program. For this we need to have a private constructor in the Class with Builder class as argument.

Here is the sample builder pattern example code where we have a Computer class and ComputerBuilder class to build it.

package com.journaldev.design.builder; public class Computer < //required parameters private String HDD; private String RAM; //optional parameters private boolean isGraphicsCardEnabled; private boolean isBluetoothEnabled; public String getHDD() < return HDD; >public String getRAM() < return RAM; >public boolean isGraphicsCardEnabled() < return isGraphicsCardEnabled; >public boolean isBluetoothEnabled() < return isBluetoothEnabled; >private Computer(ComputerBuilder builder) < this.HDD=builder.HDD; this.RAM=builder.RAM; this.isGraphicsCardEnabled=builder.isGraphicsCardEnabled; this.isBluetoothEnabled=builder.isBluetoothEnabled; >//Builder Class public static class ComputerBuilder < // required parameters private String HDD; private String RAM; // optional parameters private boolean isGraphicsCardEnabled; private boolean isBluetoothEnabled; public ComputerBuilder(String hdd, String ram)< this.HDD=hdd; this.RAM=ram; >public ComputerBuilder setGraphicsCardEnabled(boolean isGraphicsCardEnabled) < this.isGraphicsCardEnabled = isGraphicsCardEnabled; return this; >public ComputerBuilder setBluetoothEnabled(boolean isBluetoothEnabled) < this.isBluetoothEnabled = isBluetoothEnabled; return this; >public Computer build() < return new Computer(this); >> > 

Notice that Computer class has only getter methods and no public constructor. So the only way to get a Computer object is through the ComputerBuilder class. Here is a builder pattern example test program showing how to use Builder class to get the object.

package com.journaldev.design.test; import com.journaldev.design.builder.Computer; public class TestBuilderPattern < public static void main(String[] args) < //Using builder to get the object in a single line of code and //without any inconsistent state or arguments management issues Computer comp = new Computer.ComputerBuilder( "500 GB", "2 GB").setBluetoothEnabled(true) .setGraphicsCardEnabled(true).build(); >> 

Builder Design Pattern Video Tutorial

Recently I uploaded a YouTube video for Builder Design Pattern. I have also explained why I think the builder pattern defined on WikiPedia using Director classes is not a very good Object Oriented approach, and how we can achieve the same level of abstraction using different approach and with one class. Note that this is my point of view, I feel design patterns are to guide us, but ultimately we have to decide if it’s really beneficial to implement it in our project or not. I am a firm believer of KISS principle. https://www.youtube.com/watch?v=D5NK5qMM14g If you like the video, please do share it, like it and subscribe to my channel. If you think I am mistaken or you have any comments or feedback so that I can improve my videos in future, please let me know through comments here or on YouTube video page.

Builder Design Pattern Example in JDK

Some of the builder pattern example in Java classes are;

That’s all for builder design pattern in java.

You can download the example code from my GitHub Repository.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Кофе-брейк #124. Паттерн проектирования Builder. Как работает сериализация и десериализация в Java

Java-университет

Кофе-брейк #124. Паттерн проектирования Builder. Как работает сериализация и десериализация в Java - 1

Источник: Medium В этой статье мы узнаем, как проектировать и создавать объекты для класса, используя паттерн проектирования Builder .

Зачем нам нужен паттерн проектирования Builder?

  1. Наличие слишком многих аргументов для передачи из клиентской программы в класс Factory может приводить к возникновению ошибок, поскольку в большинстве случаев тип аргументов здесь один и тот же, а со стороны клиента трудно поддерживать порядок аргументов.
  2. Некоторые параметры могут быть необязательными, но в паттерне Factory мы вынуждены отправлять все параметры, а необязательные параметры необходимо отправлять как файлы NULL.
  3. Если объект “тяжелый” и со сложной разработкой, то все эти трудности станут частью классов Factory, что часто приводит к путанице.

Что такое паттерн проектирования Builder?

Паттерн Builder решает проблему с большим количеством необязательных параметров и непоследовательных состояний, предоставляя способ пошагового создания объекта. Для этого используется метод, который фактически возвращает окончательный объект.

Как реализовать паттерн проектирования Builder в Java?

  1. Создайте статический вложенный класс ( static nested class ) как класс Builder , а затем скопируйте все поля из внешнего класса в класс Builder . Мы должны следовать соглашению об именах, поэтому если имя класса Person , то класс Builder должен называться как PersonBuilder .
  2. Класс Builder должен иметь общедоступный конструктор со всеми необходимыми полями в качестве параметров.
  3. Класс Builder должен иметь методы для установки необязательных параметров, и он должен возвращать тот же объект Builder после установки необязательного поля.
  4. Последним шагом является предоставление метода build() в классе Builder , который будет возвращать объект, необходимый клиентской программе. Для этого нам нужно иметь частный конструктор в основном классе с классом Builder в качестве аргумента.

Пример:

 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 : в java.lang.StringBuilder и java.lang.StringBuffer использовали шаблон Builder для построения объектов.

Как работает сериализация и десериализация в Java

Источник: Medium Я перешел на Java в январе этого года после стажировки. До этого я в основном писал на PHP и немного на JavaScript. Ранее мне не приходилось сталкиваться с сериализацией, хотя на самом деле сериализация существует и в PHP. Правда, в Java она используется намного чаще. Сегодня я познакомлю вас, как работает сериализация и десериализация в Java и расскажу о нескольких способах их применения.

Что такое сериализация и десериализация

Сериализация — это преобразование объекта из класса в последовательность байтов на виртуальной машине Java (JVM) для передачи на другую виртуальную машину Java. Если виртуальная машина Java воссоздает объект из байтов, то этот процесс называется десериализацией.

Пример сериализации и десериализации

Сериализация

 import java.io.*; public class Person implements Serializable < int name = "empty"; public Person(int identity, String nomenclature) < name = nomenclature; id = identity; >> 

Класс Person реализует Serializable , чтобы его объект можно было сериализовать/десериализовать. Класс Person имеет два поля: идентификатор и имя, которые изменяются от значения по умолчанию при создании экземпляра класса. В пакет Java.io были импортированы интерфейс Serializable и другие классы, используемые в программе.

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

Как вы знаете, основной метод запускает сериализацию и выводит сообщение об успешном результате, в противном случае печатается сообщение об ошибке. Для сериализации объектов мы используем ObjectOutputStream и метод writeObject .

Десериализация

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

Десериализация является обратным действием по отношению к сериализации. Для восстановления объекта из последовательности байтов используется ObjectInputStream и метод readObject . Заметьте, что для обеспечения доступа к полям в классе Person объект приведен к типу данных Person . Объект класса, который не реализует интерфейс сериализации, не может быть сериализован. Поэтому любой класс, который ссылается на класс, реализующий интерфейс сериализации, должен сам реализовывать интерфейс сериализации, иначе будет выдано исключение. Сериализация не зависит от платформы, то есть сериализуемый поток байтов может десериализоваться другой виртуальной машиной Java. Статические и переходные поля не сериализуются, поэтому если у вас есть поле, которое вы не хотите сериализовать, сделайте его временным или статическим. В случае статического поля оно не сериализуется, потому что статическое поле принадлежит классу, а не объекту. Из-за этого переходное состояние предотвращает сериализацию поля. Сериализация применяется в Hibernate, JPA и RMI. Сериализацию также можно настроить. Это называется пользовательской сериализацией.

Источник

Читайте также:  Разрешить вывод ошибок php
Оцените статью