The Builder Pattern (using immutability)
The Builder Pattern
Example from Joshua Bloch's book: Effective Java
Design Patterns Github: https://github.com/prof-fontanez/Design-Patterns-Examples
Benefits:
1) Better alternative to the JavaBeans pattern because it doesn't preclude making the class immutable.
2) Allows the object to be built in steps rather than all in one. (You may have scenarios where it might be undesirable to provide a partially configured object.)
3) - If immutable - provides thread safety
This pattern is also well-suited for class hierarchies (will show on a future video)
The blueprint:
1) Create your widget class, but make the constructor private.
2) Constructor must take a Builder as an argument.
2a) Initialize all fields by obtaining the data from the builder object.
3) Add all your data members (fields). Optionally, make them all final (code for immutability).
4) Add getters. Add setters unless coding for immutability.
4a) getters should return either an immutable object or a defensive copy (clone)
4) Include the Builder class as a public static inner class.
5) In the builder, declare all the fields found in the widget class.
5a) Required fields shall be final.
6) Create the Builder constructor taking all required fields as parameters.
7) Add "setters" for each optional member, but make the method return the Builder.
8) Lastly, add a "build()" method on the Builder that returns a new instance of the widget being built.
9) Optionally (although you always should), override equals(), hashCode(), and toString() methods, etc.
Cons:
1) Can be more verbose than telescoping constructors.
2) Can be a problem in performance-critical situations. (I have never experienced this).
3) - If immutable - you might end up creating a lot of instances over the life of the program.
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «The Builder Pattern (using immutability)», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.