Besides, the acceleration ability also decreases, the car''''s engine sound will also change less than in other states.Besides, in Sport mode, fuel consumption will be higher than normal fu
Introduction
In Part 2, our team progressed from the initial exploration of UML diagrams and introduced different Design Patterns (DPs) in Object- Oriented Analysis and Design (OOAD) We have now divided our team into separate tasks, each focusing on different aspects of the project.
For this report, I will choose a real-life scenario from the Design Patterns phase that my team presented earlier, and I will demonstrate how to apply it using the corresponding class diagram developed by your team Our project is about OOPing the Car object when applying DP as State when implementing it in code
Scenario
Nowadays, means of transportation are becoming more and more modern to meet everyone's personal travel needs As an Automobile manufacturing corporation, we want to have software that can provide all customers with information about the car including its characteristics, status and actions in that state.
In the car's eco mode, the car's fuel consumption will decrease compared to other modes Besides, the acceleration ability also decreases, the car's engine sound will also change less than in other states.
Besides, in Sport mode, fuel consumption will be higher than normal functions but at the same time will provide faster acceleration compared to other vehicle states In addition, the car's engine sound will be louder when entering sport mode.
Performance: In the "Normal" state engine power is often optimized to provide higher performance For example, motor power can be increased to about 7km/h.
Fuel consumption: "Normal" state usually consumes more fuel than "Eco" due to the increase in power and specific speed of about 0.4L/7km.Make engine sound: when in Normal state, engine noise will be 90 dB
The maximum speed that the car can reach in Normal state is 120 km/h when overtaking accelerate and there is a risk of overspeeding The program will issue a warning to the user
Performance: In "Eco" mode, engine power is typically limited to optimize fuel consumption For example, motor power can be reduced to about 5km/h.
Fuel Efficiency: "Eco" status typically provides better fuel efficiency For example, in this state, the car can run about 0.3l/5km of fuel in normal traffic conditions.Make engine sound: when in Eco estate, engine noise will be 70 dB
The maximum speed that the car can reach in Eco state is 100 km/h when overtaking accelerate and there is a risk of overspeeding The program will issue a warning to the user
Performance: In "Sport," engine output is typically optimized to provide greater performance For example, motor power can be increased to about 10km/h.
Fuel consumption: "Sport" status usually consumes more fuel than "Eco" due to the increase in power and specific speed of about 0.5l/10km Make engine sound: when in Sport state, engine noise will be 100 dB
The maximum speed that the car can reach in Sport state is 150 km/h when overtaking accelerate and there is a risk of overspeeding The program will issue a warning to the user
Break: in all states when the user steps on the brake, the vehicle's speed will gradually decrease and each time it decreases by 7km/h.
Fuel warning: If the fuel during operation drops below 10 liters, the program will issue a message meaning that fuel is low, and suggest switching to Eco state (This warning will not appear if the vehicle is in Eco state).When the fuel drops to 5 liters, the Program will broadcast a notification every time the vehicle speed increases, warning that it is low on fuel When it reaches 0, the program will play the final message and the speed will gradually decrease even if the user presses the acceleration button.
This internal interface lays down a set of rules that any car state must follow It encompasses a range of methods and properties to define the behavior of different car states These include:
IncreaseAcceleration(Car car): A method that influences how the car accelerates.
FuelConsumption(Car car): A method that calculates the fuel consumption of the car.
CalculateEngineNoise(Car car): A method that determines the engine noise based on the car's current state.
GetMaxSpeed(): A method that provides the maximum speed allowed for the state.
GetName(): A method that retrieves the name of the current state
The Car class represents a virtual car and has various properties and methods to manage its state and behavior The class includes:
Speed: Represents the current speed of the car.
Fuel: Represents the remaining fuel in the car.
MaxSpeed: A boolean indicating whether the car is currently at its maximum speed. currentState: Stores the current state of the car, implementing the ICarState interface.
The constructor takes an initial state as a parameter and initializes the fuel level.
SetState(ICarState newState): Changes the current state of the car.
Brake(): Decreases the car's speed when the brake is applied.
CheckMaxSpeed(): Checks if the car has reached its maximum speed based on the current state.
CalculateFuelConsumption(): Calculates the fuel consumption based on the current state.
CalculateEngineNoise(): Calculates the engine noise based on the current state.
GetCurrentStateName(): Gets the name of the current state.
WarnMaxSpeed(): Checks if the car is at its maximum speed and provides a warning to reduce speed if necessary. CheckFuel(): Monitors the fuel level and triggers warnings and state changes if fuel is low or empty.
These classes represent different states that a car can be in, and they implement the ICarState interface.
Each class defines specific behavior for increasing acceleration, calculating fuel consumption, calculating engine noise, getting the maximum speed, and getting the state's name For example, the NormalState allows acceleration up to a maximum speed of
120, has a fuel consumption rate of 0.4, and calculates engine noise based on the car's speed.
Implementation
Code
The interface is the first step in outlining basic behaviors and information related to the car's state Below is a detailed explanation of each part of the interface:
Acceleration(Car): This method is used to increase the acceleration of the car It takes a Car object as a parameter and can modify the car's state to change its acceleration.
FuelConsumption(Car): This method returns the car's fuel consumption It takes a Car object as a parameter and returns a double value representing the amount of fuel consumed.
CalculateEngineNoise(Car): This method calculates the car's engine noise level It takes a Car object as a parameter and returns the estimated engine noise level as a double value.
GetMaxSpeed(): This method returns the maximum speed that the car can achieve It does not take any parameters and returns an int value.
GetName(): This method returns the vehicle name or model It does not take any parameters and returns a string representing the car name.
This is the EcoState class which is 1 of 3 subclasses of the ICarState interface This means that the EcoState class must provide concrete implementations of all methods and properties defined in the ICarState interface.
Public void IncreaseAcceleration(Car): This is an implementation of the IncreaseAcceleration method required by the ICarState interface In this implementation, it will increase the car's speed by 5 units if the current speed is less than the maximum speed (GetMaxSpeed()).
It also checks and limits the speed to the maximum speed if that limit is exceeded With each different state there will be a different speed increase
Figure 4 - Acceleration in Car class
This car class will have all the properties of a normal car, including normal functions and functions that change depending on the state it carries. public void Accelerate(): This method represents the vehicle's acceleration action.
Here there will be a combination of several results of different functions, specifically the result of void FuelConsumption() it will return different results based on the current state of the car
There will be several conditions under which the results of void FuelConsumption() can be divided Under a certain condition, the vehicle will accelerate according to the preset acceleration.
CheckMaxSpeed();: This method checks and has the ability to limit the car's speed to the maximum allowable speed.
If there is no fuel (other block), the car's speed is reduced by 3 units This simulates deceleration due to running out of fuel.WarnMaxSpeed();: This method seems to be responsible for giving a warning or taking action when the vehicle reaches maximum speed Every time you press acceleration, it will check whether the maximum speed has been reached or not If so, a notification will be displayed on the screen
Figure 5 - Button Acceleration in form
This is the event handler when the btnSpeed_Click_1 button is clicked The creation of this button is intended for users to be able to accelerate the Car object according to the acceleration function
In this button there are called functions such as car.CheckFuel(); : this is calling the car object and using the fuel check function to see if there is no fuel If the fuel has not yet run out, no event will occur Otherwise, a notification will be sent to the user via the screen and give options to the next user. car.Accelerate(); : This will be the main purpose when creating a button to accelerate the Car object according to what has been programmed and also depends on the current state of the object.
Figure 6 - Update UI in form UpdateUI(); : this will be the function created in the form cells that display data each time any button is pressed The purpose is to update the data in the interface
Figure 7 - Fuelconsumption in EcoclassPublic double FuelConsumption(Car car): This method is an implementation of the FuelConsumption method defined in the ICarState interface It takes a Car object as a parameter, representing the car whose fuel consumption is being calculated.Return 0.3;: In this implementation, the FuelConsumption method returns the constant value of 0.3 This means that, while the car is in this state, the speed or any other factor of the car, fuel consumption is always set at 0.3.
Figure 8 - Fuel calculation double fuelConsumption = currentState.FuelConsumption(this);: This line calculates the fuel consumption by calling the FuelConsumption method of the current state (stored in the currentState variable) The this keyword is used to refer to the current Car object. if (Fuel > 0) { }: This section of code checks if there is any fuel left in the car's fuel tank If there is fuel, the car can accelerate.
Fuel -= fuelConsumption;: This line subtracts the calculated fuelConsumption from the car's fuel tank, representing the fuel consumption during acceleration If the calculated consumption depletes the fuel completely (fuel becomes negative), it sets the fuel level to 0 to ensure it doesn't go negative. else { }: If there's no fuel left (i.e., Fuel is 0 or negative), the car's speed is reduced by 3 units.
Speed = Math.Max(0, Speed - 3);: This line sets the car's speed to the greater of 0 and the current speed minus 3 This ensures that the speed doesn't go below 0.
Figure 9 - Update UI for fuel After being called in and processing the information carefully, like displaying the speed on the display bar The remaining fuel in the car will be updated when pressing any button that affects the car's current fuel.
Program screenshots
The following is a screenshot of our running program We have 4 labels to represent the textbox bars with their data such as: Speed, Noise, State and Fuel
There are 3 more text boxes behind to show that fuel will be calculated in L, speed will be calculated in Km/h and vehicle noise will be calculated in dB.
Figure 11 - After Click Normal button
There are 5 buttons that display changes in the vehicle's status When selecting Normal mode.
The vehicle will display Normal data including current speed, vehicle's remaining fuel, and vehicle's current engine noise With the same function State buttons also display the same vehicle data.
Figure 12 - Click Speed button Each time you click on speed, the speed will increase by 7km/h and after each click on Break The vehicle speed will decrease to 7km/h if you press the brake button on the interface Noise and fuel will vary according to the vehicle's current speed.
In Normal state, the maximum speed that the car can reach is 120km/h If the user still presses the acceleration button, the program will display a warning "You are running at maximum speed Do you want to slow down?
Similar to the normal state, other states such as eco and sport also have a maximum speed mark to issue warnings to the user.
If the vehicle's fuel is less than 10L, a message will display "Out of gas! Switch to Eco mode?”, “Fuel warning” and there will be a screen to switch fuel economy state to Eco or not.
If you select yes, it will be displayed to Eco state, if not selected, you are still in active state.
If you are already in the car's eco mode, the warning will not be sent to the user
Figure 15- Fuel refill warning and Low fuel warning
After the fuel level drops below 5L, there will be another warning sent to the user: "Out of gas! Please refuel soon", "Fuel warning"
When it reaches 0L, the message "Out of fuel! Vehicle has stopped" will appear is displayed "Fuel warning" when the user clicks on the speed, the speed decreases by 3km/h each time and if the brake is pressed, the speed still decreases by 7km/h.
Discussion
Range of similar patterns
A quick overview of a similar trend Explain why the pattern is the best fit for your situation similar pattern:Abstract Factory
Make things with specified attributes: The "Abstract Factory" template allows you to make objects with specific properties of automobiles in each state For example, you might design an Abstract Factory for the "Eco" state and another for the "Sport" state, with each Factory producing things (e.g., fuel consumption objects) appropriate for that condition.
Separation of interface and implementation: The "Abstract Factory" design divides an abstract factory's interface from the actual implementation of its concrete factories This allows you to easily alter or extend the way objects are formed without having to update the main source code.
Manage different car states and properties: With different car states and properties (Eco mode and Sport mode), the "Abstract Factory" template allows you to manage all states and properties efficiently and simply in the future.
Simple product expansion: If you wish to add additional states or attributes to your product in the future, the "Abstract Factory" template allows you to do so without modifying the entire system.
Optimize performance and resources: Using this pattern, you may optimize the production of state-specific objects and information, allowing you to conserve resources and enhance speed.
The reason why we choose state pattern.
Managing vehicle states: Your project necessitates the management of several vehicle states, including "Eco," "Normal," and
"Sport." The State Design Model enables you to simply monitor and alter the state of the vehicle without the need for elaborate if-else control statements.
Use the State Design approach to construct different state classes for each vehicle state, making project code easier to manage This makes the code easier to maintain since you can focus on each state independently rather than having to alter the whole code every time a modification or expansion of a specific state's capability happens.
Ease of extension: If you wish to add more states to your vehicle in the future, the State Design paradigm allows you to do so without altering existing code This allows the project to easily expand and react to changes in product needs
Separating state logic: This model helps you separate the processing logic for each state from each other This makes the source code easier to read and understand and reduces the risk of bugs due to the interference of logic between states.
Usage of pattern
In my program there are some advantages and disadvantages as follows:
Clear and understandable: Pattern State defines a straightforward and comprehensible method for managing an object's state and changing its behavior based on the state As a result, the source code is easier to understand and maintain.
Easily extensible: We can simply add additional states and behaviors to Pattern State without affecting the existing source code This makes it simple to grow the application.
Integration with other patterns: Pattern State clearly separates state and behavior, helping you maintain design consistency.
Large number of state layers: Many state layers may exist in big or sophisticated applications, resulting in an increasing number of layers that are difficult to maintain Managing numerous levels of status may be difficult.
Difficult to debug: When you need to update a section of the behavior or add a new state, you may need to change several separate classes, which might lead to issues.
Not suitable for all types of applications: Pattern State should be used when an object has numerous states and behavior that is dependent on the state In certain basic scenarios, employing Pattern State might add unnecessary complexity to the code.