0% found this document useful (0 votes)
24 views

DesingPatterns-LiveCodingSession-1-Builder and Prototype

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

DesingPatterns-LiveCodingSession-1-Builder and Prototype

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

The Builder and Prototype

design patterns

Design & Tests 1


In this lesson

22
Contents

• Object-Oriented Design patterns


– Builder
– Prototype

3
To help us on designing applications we (re-)use

ARCHITECTURAL DESIGN PATTERNS SOFTWARE


STYLES FRAMEWORKS

4
Now, we want to focus on the detailed design:
How should I organize my code?
On which method/class should I put my code?

5
Design patterns

A pattern is a general
Descripción de lossolution to a recurring
subsistemas design problem
y componentes de that expresses a
un sistema
relationship
softwarebetween
y de lasainterrelaciones
context, a problem, andellos.
entre a solution.

A pattern is not a complete solution but a guide/skeleton that must be adapted to


each specific problem.

Intuitive Idea: "When you find this problem, apply this solution”.

Problem Solution
7
Catalog of design patterns of interest for game design

In this
session:

10
Design Pattern: Builder

Intent: Builder lets you construct complex objects step by step. The pattern allows
you to produce different types and representations of an object using the same
construction code.

11
Design Pattern: Builder

Problem: Complex objects require laborious step-by-step initialization of many


fields and nested objects. Such initialization code is usually buried inside a
monstrous constructor with lots of parameters or scattered all over the client code.

12
Design Pattern: Builder

Applicability: class Pizza {


• Get rid of giant constructors Pizza(int size, boolean cheese, boolean pepperoni,
boolean bacon, boolean pineapple, …) { ... }
invocations (except for
// ...
the builder): new Pizza(10,true,false,true,false,…);

• Get rid of telescopic constructors:


class Pizza {
Pizza(int size) { ... }
Pizza(int size, boolean cheese) { ... }
Pizza(int size, boolean cheese, boolean pepperoni) { ... }
// ...

• Get rid of endless sequence of setters: Pizza p=new Pizza(BIG);


p.setExtraCheese(gorgonzola);
p.setBacon(true);
p.setPepperoni(true);
// ... 13
Design Pattern: Builder

Solution: The Builder pattern suggests that you


extract the object construction code out of its
own class and move it to separate objects
called builders.
Some construction steps might require different
implementations. For example, walls of a cabin
may be built of wood, but the castle walls must
be built with stone.
You can create different builder classes that
implement the same set of building steps. You
can use these builders in the construction
process (i.e., an ordered set of calls to the
building steps) to produce different kinds of
objects.

14
Design Pattern: Builder

Example:

Request userRequest =RequestBuilder


.get("http://somewhere.com/api/users/{param1}")
.with(userId1)
.build();

// ...

Request allUsersRequest=RequestBuilder
.get("http://somewhere.com/api/users")
.withoutParameters()
.build();

Show RequestBuilders en Controller Test (React PetClinic)


15
Design Pattern: Builder
public class CarBuilder implements Builder {
• Implementation: private CarType type;
private int seats;
public interface Builder { private Engine engine;
Builder ofType(CarType type); private Transmission transmission;
Builder seats(int seats); private TripComputer tripComputer;
Builder engine(Engine engine); private GPSNavigator gpsNavigator;
Builder transmission(Transmission transmission);
Builder tripComputer(TripComputer tripComputer); public static Builder ofType(CarType type) {
Builder gpsNavigator(GPSNavigator gpsNavigator); new CarBuider(type);
Car build(); @Override
} public Builder seats(int seats) { this.seats = seats; }

public Car build() {


return new Car(type, seats, engine, transmission,
tripComputer, gpsNavigator); }
}

• Use:
CarBuilder.ofType(CarType.COUPE)
.seats(4)
.engine(new TurboEngine());
.transmission(new AutomaticTransmission())
.build();
16
Design Pattern: Builder

17
Design Pattern: Builder

Advantages
• You can construct objects step-by-step, defer construction steps or run steps
recursively.
• You can reuse the same construction code when building various
representations of products.
• You can isolate complex construction code from the business logic of the
product.

Drawbacks
• The overall complexity of the code increases since the pattern requires creating
multiple new classes.

18
WHERE WHOULD YOU APPLY THIS PATTERN IN THE/YOUR
SOFTWARE IMPLEMENTATION OF A BOARD GAME?

19
Design Pattern: Prototype (a.k.a. Clone)

Intent: Prototype is a creational design pattern that lets you copy


existing objects without making your code dependent on their classes

20
Design Pattern: Prototype

Problem: You have an object, and you want to create an exact copy of it.
Approach:
1.- Create a new object of the same class.
2.- Copy the values of the fields
But … some of the fields may be private and not visible from outside. Moreover, your
code becomes dependent on the class of the original object, and sometimes you only
know the interface of the object. 21
Design Pattern: Prototype
The Prototype interface
Structure: declares the cloning
methods. In most cases,
it’s a single clone method.

The Concrete Prototype class


implements the cloning method. In
addition to copying the original object’s
data to the clone, this method may also
handle some edge cases of the cloning
process related to cloning linked objects,
untangling recursive dependencies, etc.

Show Shapes (Circle, Rectangle) example in Refactoring.guru!!


22
Design Pattern: Prototype

Advantages
• You can clone objects without coupling to their concrete classes.
• You can get rid of repeated initialization code in favor of cloning
pre-built prototypes.
• You can produce complex objects more conveniently.
• You get an alternative to inheritance when dealing with
configuration presets for complex objects.

Drawbacks
• Cloning complex objects that have circular references might be very
tricky.

23
WHERE WHOULD YOU APPLY THIS PATTERN IN THE/YOUR
SOFTWARE IMPLEMENTATION OF A BOARD GAME?

24
Reminders

25
A+ Criteria published

26
Sneak peak on some A+ criteria: a hard one

“Integration of an alternative view technology such as Thymeleaf, Angular, React,


or Vue.js”.

➔Except for Thymeleaf, It usually implies the implementation of some other A+ criteria
such as “Implementation of REST API controllers for at least 3 of the application
services, and invocation of these from the client through AJAX calls”

27
Sneak peak on some A+ criteria: an easy one
@StatePattern
“Specification of the application of public class StatePatternApplication {
the design patterns in the project @StatePattern.State
interface SpeedLevel {
using the jpatterns library” void rotate(FanWallControl fanWallControl);}

@StatePattern.Context
static class FanWallControl {
<dependency> private SpeedLevel current;
<groupId>org.jpatterns</groupId>
<artifactId>jpatterns</artifactId> @StatePattern.ConcreteState
<version>0.0.1</version> static class Off implements SpeedLevel {
</dependency> public void rotate(FanWallControl fanWallControl) {
fanWallControl.set_state(new SpeedLevel1());
}
}
@StatePattern.ConcreteState
You have several examples available at static class SpeedLevel1 implements SpeedLevel {
the japatterns branch of the template public void rotate(FanWallControl fanWallControl)
fanWallControl.set_state(new SpeedLevel2());
{

repository. Available at: }


}

@StatePattern.ConcreteState
https://github.com/gii-is-DP1/spring- static class SpeedLevel2 implements SpeedLevel {
public void rotate(FanWallControl fanWallControl) {
petclinic/tree/jpatterns/src/main/java/org/s fanWallControl.set_state(new SpeedLevel3());
pringframework/samples/petclinic/patterns }
}
@StatePattern.ConcreteState
static class SpeedLevel3 implements SpeedLevel {
public void rotate(FanWallControl fanWallControl) {
fanWallControl.set_state(new Off()); 28
} } }
References

29
Bibliography

Martin Fowler, David Rice. Patterns of Enterprise


Application Architecture. Addison-Wesley Professional. 3rd
edition. 2003 (Chapters 1, 4 & 14)

Design Patterns by Refactoring Guru


Available at: https://refactoring.guru/design-patterns/

30
Bibliography

Rober C. Martin. Clean Code: A Handbook of Agile Software


Craftsmanship. Prentice Hall. 2009 (Chapters 1 & 2)

Eric Freeman & Elisabeth Jonson. Head First: Design


Patterns. O’Reilly. 2014. (Chapters 1, 3, 6, 10 & Appendix A)

31
Bibliography

John P. Doran, Matt Casanova. Game Development


Patterns and Best Practices. Packt Publishing. 2017

Robert Nystrom. Game Programming Patterns. Genever


Benning. 2014

32
Disclaimer and Terms of Use

All material displayed on this presentation is for teaching and personal use only.

Many of the images that have been used in the presentation are Royalty Free images
taken from http://www.everystockphoto.com/. Other images have been sourced directly
from the Public domain, from where in most cases it is unclear whether copyright has
been explicitly claimed. Our intention is not to infringe any artist’s copyright, whether
written or visual. We do not claim ownership of any image that has been freely obtained
from the public domain. In the event that we have freely obtained an image or quotation
that has been placed in the public domain and in doing so have inadvertently used a
copyrighted image without the copyright holder’s express permission we ask that the
copyright holder writes to us directly, upon which we will contact the copyright holder to
request full written permission to use the quote or images.

You might also like