TP 2 Creational Patterns 24 - 25
TP 2 Creational Patterns 24 - 25
Exercise 1:
Create a builder for a class, that has the following fields:
public class Dog {
private String name;
private String type;
private Integer age;
private List<String> toys;
Builder should be defined inside the class Dog and should be the only of creating its
instance.
Exercise 2:
In order to put the Singleton pattern into practice, let's take a short example of
implementation in the banking industry. First of all, we will design a Bank Account
class that allows you to deposit or withdraw money on an account. But we would like
to be able to display the operations (performed or refused) in the console in case of
dispute (it would also be possible to use a text file as output). This small application
will have to evolve quickly and it is very likely that later other classes will be
concerned by this logging. For this, we will implement a separate class named
Logging using the Singleton pattern. Thus we will guarantee that our program will use
a single instance of the Logging class. A third class entitled Main will make it possible
to run the application and obtain a result in console.
Let’s consider a scenario where you’re developing a game that has multiple types of
characters, each with its own attributes like health, weapons, and abilities. These
characters are costly to create due to the amount of configuration involved.
Instead of creating every character from scratch, we clone a prototype and adjust its
specific attributes. This is much more efficient when characters share many common
features.
1. Describe how we can do this with the diagram illustrating the pattern, then write
the code in java.
Exercise 4:
You need to create a library to manage different types of vehicles, such as cars,
motorcycles and bicycles. Vehicles share some common features (for example, they
have wheels, an engine, etc.), but each type of vehicle has specific characteristics
(for example, cars have a number of doors, motorcycles have a number of cylinders,
etc.). Use the Pattern Factory Method to implement this library.
1. Draw the class diagram illustrating the use of this pattern.
2. Write the corresponding Java code.