You are on page 1of 41

ASSIGNMENT 1

Qualification BTEC Level 5 HND Diploma in Computing

Unit number and title Unit 20: Advanced Programming

Submission date 01/05/2024 Date Received 1st submission

Re-submission Date Date Received 2nd submission

Student Name Trần Hữu Vương Student ID GCH190643

Class GCH1108.1 Assessor name Le Viet Bach

Student declaration

I certify that the assignment submission is entirely my own work and I fully understand the consequences of plagiarism.
I understand that making a false declaration is a form of malpractice.

Student’s signature

Grading grid

P1 P2 M1 M2 D1 D2

1
 Summative Feedback:  Resubmission Feedback:

Grade: Assessor Signature: Date:


Lecturer Signature:

2
Table of Contents
Table of figure ............................................................................................................................................................... 5

1. Introduction ............................................................................................................................................................... 7

2. OOP general concepts ............................................................................................................................................... 7

2.1. Introduction of OOP........................................................................................................................................... 7

a) History of OOP.................................................................................................................................................. 7

b) Definition of OOP. ............................................................................................................................................ 7

2.2. OOP general concepts........................................................................................................................................ 8

a) Objects............................................................................................................................................................... 8

b) Class .................................................................................................................................................................. 8

c) Inheritance ......................................................................................................................................................... 9

d) Polymorphism ................................................................................................................................................. 10

e) Abstraction ...................................................................................................................................................... 11

f) Encapsulation................................................................................................................................................... 12

g) Aggregation..................................................................................................................................................... 13

h) SOLID ............................................................................................................................................................. 13

Single responsibility principle ............................................................................................................................. 13

Open/closed principle .......................................................................................................................................... 14

Liskov substitution principle ............................................................................................................................... 14

Interface segregation principle ............................................................................................................................ 15

Dependency inversion principle .......................................................................................................................... 16

3. OOP scenario........................................................................................................................................................... 17

3.1. Scenario ............................................................................................................................................................ 17

3.2. Usecase diagram .............................................................................................................................................. 18

Explain gym manager system: ............................................................................................................................. 18

3
3.3. Class diagram .................................................................................................................................................. 24

Explain: ............................................................................................................................................................... 24

4. Design Patterns ........................................................................................................................................................ 25

4.1. Creational pattern ............................................................................................................................................ 25

a) Singleton ......................................................................................................................................................... 26

b) Abstract Factory .............................................................................................................................................. 27

c) Prototype ......................................................................................................................................................... 28

d) Group scenario ................................................................................................................................................ 29

e) Diagram ........................................................................................................................................................... 30

Explain: ............................................................................................................................................................... 30

4.2. Structural pattern ............................................................................................................................................. 30

a) Bridge .............................................................................................................................................................. 31

b) Decorator......................................................................................................................................................... 32

c) Adapter ............................................................................................................................................................ 33

d) Group scenario ................................................................................................................................................ 34

e) Diagram ........................................................................................................................................................... 35

Explain: ............................................................................................................................................................... 35

4.3. Behavioral pattern............................................................................................................................................ 35

a) Observer .......................................................................................................................................................... 36

b) Chain of Responsibility ................................................................................................................................... 37

c) Strategy ........................................................................................................................................................... 38

d) Group scenario ................................................................................................................................................ 39

e) Diagram ........................................................................................................................................................... 40

Explain: ............................................................................................................................................................... 40

5. Design Pattern vs OOP ............................................................................................................................................ 40

4
6. Conclusion ............................................................................................................................................................... 41

7. Reference ................................................................................................................................................................. 41

Table of figure
Figure 1: OOP concepts (javatpoint.com) ..................................................................................................................... 8

Figure 2: Example of object and class. .......................................................................................................................... 9

Figure 3: Example of Inheritance. ............................................................................................................................... 10

Figure 4: Example of Polymorphism............................................................................................................................ 11

Figure 5: Example of Abstraction. ............................................................................................................................... 12

Figure 6: Access levels. ................................................................................................................................................ 12

Figure 7: Example of Encapsulation. ........................................................................................................................... 13

Figure 8: Example of Aggregation. .............................................................................................................................. 13

Figure 9: Single responsibility principle’s example. .................................................................................................... 14

Figure 10: Open/Close principle's example. ................................................................................................................ 14

Figure 11: Violation of Liskov substitution principle. .................................................................................................. 15

Figure 12: No violation of Liskov substitution principle. ............................................................................................. 15

Figure 13: Interface segregation principle's example. ................................................................................................ 16

Figure 14: Dependency inversion principle's example. ............................................................................................... 16

Figure 15: Usecase diagram. ....................................................................................................................................... 18

Figure 16: Class diagram.............................................................................................................................................. 24

Figure 17: Example of Singleton. ................................................................................................................................. 26

Figure 18: Example of Abstract Factory. ..................................................................................................................... 27

Figure 19: Example of Prototype (refactoring.guru) ................................................................................................... 29

Figure 20: Creational design pattern scenario diagram. ............................................................................................. 30

5
Figure 21: Example of Bridge...................................................................................................................................... 32

Figure 22: Example of Decorator................................................................................................................................. 33

Figure 23: Example of Adapter. ................................................................................................................................... 34

Figure 24: Structural design pattern scenario diagram. .............................................................................................. 35

Figure 25: Example of Observer. ................................................................................................................................. 37

Figure 26: Example of Chain of responsibility. ............................................................................................................ 38

Figure 27: Example of Strategy. .................................................................................................................................. 39

Figure 28: Behavioral design pattern scenario diagram. ............................................................................................ 40

6
1. Introduction
In this report, we illustrate a hypothetical scenario to demonstrate the application of object-oriented
design and analysis in understanding the core principles of object-oriented programming (OOP). This
example elucidates key OOP concepts such as abstraction, polymorphism, inheritance, and encapsulation.
We present diagrams and code snippets for each wallet, showcasing their OOP characteristics to facilitate
better comprehension.

In the subsequent assignment, participants are tasked with creating various UML class diagrams for object-
oriented analysis and design, including use case diagrams, class diagrams, sequence diagrams, activity
diagrams, state diagrams, and flowcharts. We provide examples for each type of diagram and offer detailed
descriptions.

Furthermore, the report guides readers through learning about different design patterns categorized into
creational, structural, and behavioral. We exemplify these patterns through real-world scenarios, illustrating
their application using UML classes and demonstrating their implementation through C# programming
techniques.

2. OOP general concepts

2.1. Introduction of OOP

a) History of OOP.
According to Purdum, J. (2008), Many individuals believe that the origins of object-oriented
programming (OOP) can be traced back to the 1980s and Bjarne Stroustrup's efforts to transform the C
language into an object-oriented one, leading to the creation of the C++ language. However, the first
instances of object-oriented languages predate this, with SIMULA 1 (1962) and SIMULA 67 (1967) being
notable examples. Ole-John Dahl and Kristen Nygaard were the pioneers behind developing the Simula
languages at the Norwegian Computing Center in Oslo, Norway. Although many of the advantages of OOP
were present in earlier Simula languages, it wasn't until the widespread adoption of C++ in the 1990s that
object-oriented programming truly gained momentum.

b) Definition of OOP.
Object-oriented programming is an approach to software development in which the structure of the
software is based on objects interacting with each other to accomplish a task. This interaction takes the form
of messages passing back and forth between the objects. In response to a message, an object can act.

If you look at how you accomplish tasks in the world around you, you can see that you interact in an object-
oriented world. If you want to go to the store, for example, you interact with a car object. A car object

7
consists of other objects that interact with each other to accomplish the task of getting you to the store. You
put the key object in the ignition object and turn it. This in turn sends a message (through an electrical
signal) to the starter object, which interacts with the engine object to start the car. As a driver, you are
isolated from the logic of how the objects of the system work together to start the car. You just initiate the
sequence of events by executing the start method of the ignition object with the key. You then wait for a
response (message) of success or failure.

(Clark, 2013)

2.2. OOP general concepts

Figure 1: OOP concepts (javatpoint.com)

a) Objects

According to Clack (2013), An object in object-oriented programming (OOP) is a data structure that
contains the operations performed on the data as well as the data itself. This makes it simpler to comprehend
and utilize the object since the procedures and data are stored in one location.

You might make a product object, for instance, if you want to monitor information about product
inventories. Data like the product name, product ID, product quantity, and product pricing would be
contained in this object. Procedures for adding new goods to inventory, changing product details, and
deleting products from inventory would also be included. You may centrally store all the information and
processes about product inventories by generating a product object.

b) Class
A class is a pattern of program code that may be utilized to create objects. It provides initial settings
for behavior (functions or methods that the class can do) and state (variables that are part of the class).

8
There are three uses for the class name.
• The actual class (the template).
• The class's default constructor, a function that creates objects.
• The kind of items that the class produced.

Figure 2: Example of object and class.

c) Inheritance
In OOP, inheritance is used to categorize the objects in your programs based on shared traits and
purposes. As a result, interacting with the items is simpler and more natural. It also simplifies programming
because it allows you to combine generic features into a parent object and inherit these traits in the child
objects. You might, for instance, create an employee object that lists every general feature that every person
in your business has. Next, you may create a manager object that has the same properties as the employee
object plus additional features specific to managers in your organization. Any modifications to the employee
object's attributes will be automatically reflected in the manager object due to inheritance.

(Clark, 2013)

9
Figure 3: Example of Inheritance.

The provided diagram illustrates the concept of inheritance in Object-Oriented Programming (OOP)
through a class hierarchy consisting of Person, Student, and Teacher. Person serves as the base class,
encompassing general attributes like Name, Age, Size, and Hair Color, which are common to both students
and teachers. Student and Teacher, as derived classes, inherit all attributes and methods from Person.
Additionally, they can possess their own specific attributes and methods such as Study(Subject) for students
and Teach(Subject) for teachers.

Inheritance facilitates code reusability and reduces redundancy by allowing subclasses to reuse existing
code, ensuring consistency, and reducing duplication. This enhances maintainability as changes made to the
base class propagate to its subclasses. Moreover, inheritance plays a crucial role in polymorphism, enabling
code to work with objects of different types.

d) Polymorphism
Polymorphism is a Greek word, meaning "one name many forms". In other words, one object has
many forms or has one name with multiple functionalities. "Poly" means many and "morph" means forms.
Polymorphism provides the ability for a class to have multiple implementations with the same name. It is
one of the core principles of Object-Oriented Programming after encapsulation and inheritance. In this
article, you'll learn what polymorphism is, how it works, and how to implement polymorphism in C#.

In fact, we can see a lot of polymorphic things. An example is blood group. We have cold blood group and
warm blood group. The cold blood group is often found in reptiles, specifically snakes. and the specific
warm-blooded type is human.

10
Figure 4: Example of Polymorphism.

e) Abstraction
The abstraction indicates that the object being edited has either a missing or incomplete
implementation. The abstraction supports classes, methods, attributes, indexers, and events. Use the
abstraction in the class definition to indicate that a class is only intended to act as the base class for other
classes and cannot be instantiated independently. Non-abstract classes that descend from the abstract class
must implement the abstract members.

Example: In the past, phones were born to serve us in connecting to talk over long distances and faster
than sending mail. Therefore, the desk phone was born to meet the needs of making calls. but desk phones
are not flexible when moving. Therefore, mobile phones were born to serve the needs of users to be
compact and portable, but mobile phones were too rudimentary and had very few functions. Later, when
people's needs are increasing, smart phones have been born to serve people in addition to calling and
mobile needs, it can also help people entertain and convenient.

11
Figure 5: Example of Abstraction.

f) Encapsulation
The encapsulation is the process of grouping or wrapping up of data and functions to perform actions
on the data into a single unit. The single unit is called a class. Encapsulation is like enclosing in a capsule.
That is enclosing the related operations and data related to an object into that object. It keeps the data and
the code safe from external interference. The main purpose or use of the encapsulation is to provide security
to the data of a class.

Figure 6: Access levels.

Example: We visit the hospital for a checkup when we are ill. After examination the doctor said we had a
cold and handed us a medicine, which included a list of medications along with instructions on how much
to take of each and when to take it. Reading medicine, we only know that there are those drugs and the dose
of each drug, how to take it at what time. If we take the right medicine, the right dose at the right time, we
will get rid of the flu, and specifically what active ingredients are inside each drug, why do we have to take
such a dose, why should we take it. We also do not know at all.

12
Figure 7: Example of Encapsulation.

g) Aggregation
When an item is aggregated, it is made up of a composite of other things that collaborate. Your
lawnmower object, for instance, is a composite of the motor, blade, wheel, and so forth things. The engine
item is a combination of several different things. The world around us is filled with numerous instances of
aggregation. One of OOP's most potent features is the ability to employ aggregation, which helps you model
and perform business processes in your applications with accuracy.

Figure 8: Example of Aggregation.

The Aircraft class in this example aggregates a list of Engine instances. This implies that one or more Engine
objects may be connected to an Aircraft object. As a result, the code is easier to read and more reusable.

h) SOLID

Single responsibility principle


Each software module or class should have only one reason to change. we can say that each module
or class should have only one responsibility to do. So, we need to design the software in such a way that
everything in a class or module has to do with a single responsibility. Clear SRP will make the layers smaller,
cleaner, and therefore easier to maintain.

Example: At school, if all students are only managed by the principal, it will lead to overcrowding and
uncontrollability for students. So, students will be divided into different classes and only one homeroom
teacher will manage their students. This helps to better manage students.

13
Figure 9: Single responsibility principle’s example.

Open/closed principle

The Open/Closed Principle (OCP), a key aspect of the SOLID principles, emphasizes the idea that
software components should be designed to allow for easy extension without requiring modification of
existing code. This means creating modules and classes that can adapt to new functionalities or
responsibilities as needed, promoting extensibility. Conversely, the principle suggests avoiding alterations
to existing classes or modules unless necessary, typically only in the case of errors.

Example: Consider a specialized camera designed primarily for capturing landscapes. If users express a
desire for additional features tailored for portrait photography, adhering to the OCP would involve
expanding the camera's capabilities by introducing new lenses specifically designed for portraits, rather than
altering or removing the existing lens to accommodate the request.

Figure 10: Open/Close principle's example.

Liskov substitution principle


The Liskov Substitution Principle (LSP) highlights that in an inheritance hierarchy, subclasses
should be substitutable for their base class without altering the behavior of the application. Therefore, it's

14
crucial to design derived class objects in a way that allows them to seamlessly replace base class objects
while maintaining the application's integrity.

Example: From a car, we can turn it into a taxi a police car, or a family car. but ordinary people will not be
able to drive only police can drive.

Figure 11: Violation of Liskov substitution principle.

Figure 12: No violation of Liskov substitution principle.

Interface segregation principle


The Interface Segregation Principle (ISP) suggests that each interface should serve a distinct
purpose, ensuring that objects are not compelled to implement interfaces irrelevant to their functionality.
Essentially, if an interface becomes too extensive, it's more probable to include methods that not all
implementers can fulfill. This principle emphasizes designing interfaces that are tailored to the specific
needs of the objects that implement them.

Example: In a vegetable market, the distributor divides the stalls for each type of vegetable they sell. 2
types of vegetables are not allowed to be sold in the same store.

15
Figure 13: Interface segregation principle's example.

Dependency inversion principle


The Dependency Inversion Principle (DIP) dictates that higher-level modules or classes should not
rely directly on lower-level modules or classes; instead, both should depend on abstractions. Furthermore,
abstractions should not be influenced by implementation details; rather, implementation details should
depend on abstractions.

Example: In a family, we have a lot of brothers, we can consider it a low-level module. high-level modules
are their parents.

Figure 14: Dependency inversion principle's example.

16
3. OOP scenario

3.1. Scenario
FitnessAlpha, an established gym recently renovated under new ownership by John, has changed to
implement a personalized gym management approach. John has brought in Paul, a fitness trainer, to
spearhead this initiative, focusing on a limited number of members and providing tailored training.

Paul, as the primary trainer, assumes responsibility for overseeing the members' training journey, including
scheduling workouts, devising dietary plans, and guiding members throughout their exercises. His role
entails closely monitoring and mentoring members to ensure optimal training outcomes.

Upon enrollment in the training program, members must adhere to the customized plans outlined by Paul,
utilizing gym equipment for their workouts. Throughout the training sessions, Paul offers continuous
support to members, assisting with exercise execution and offering advice on effective dietary practices.
Periodically, members undergo health assessments to evaluate their progress, enabling Paul to modify their
training plans if necessary.
The management structure involves a collaborative effort between John and Paul, with a clear delineation
of responsibilities:

• To facilitate the management process, personal information of trainer and members will be
collected. With this, coaches and members can conveniently exchange training plans with each other.

• When members register for a training course, the coach will provide a suitable exercise plan for each
member (depending on the member's height, weight, and physical condition).

• Trainers and members both receive course information such as course validity period, course
schedule, course cost, trainer information.

• The members will have to follow the exercise and diet plan that the coach has set. During practice,
students can ask for support from the coach.

• Coaches and members are free to use equipment in the gym for training purposes.

• After a period, the members will report to the coach about their body condition so that the trainer can
understand the results of the training process.

• The trainer is responsible for adjusting the members' training plans to match the training results
reported by the members.

17
3.2. Usecase diagram

Figure 15: Usecase diagram.

Explain gym manager system:

Name of Use Case Create Schedule

Created By Group 2 Last Update By Nguyen Minh Duc

Date Created 08/04 Last Revision Date

Description Trainers can create and schedule courses for them

Actor Trainer

Preconditions The course must have at least one customer

18
Postconditions

Flow Register for the course.

See information about the training time

Alternative Flows

Exceptions Do not register for the course

Requirements Paid for the course with the Gym owner

Name of Use Case Create Diet Chart

Created By Group 2 Last Update By Nguyen Minh Duc

Date Created 08/04 Last Revision Date

Description Trainers can create science-based diet charts

Actors Trainer

Preconditions Attended the course

Postconditions

Flow Attended the coach's course.

Eat according to the given diet chart


Alternative Flows

Exceptions Students do not follow the diet chart

Requirements Students are required to follow the diet chart

Name of Use Case Training

Created By Group 2 Last Update By Nguyen Minh Duc

Date Created 08/04 Last Revision Date

19
Description The trainer will guide his students to practice the exercises in each course.
Give feedback and report back on your training results

Actors Trainer

Preconditions The trainer will not be allowed to be absent

Postconditions

Flow After choosing the course, the trainer begins to guide the students to
practice.

Then record and report the results of the exercise


Alternative Flows

Exceptions

Requirements Students practice hard, and eat according to the given chart

Name of Use Case View Workout Plan

Created By Group 2 Last Update By Nguyen Minh Duc

Date Created 08/04 Last Revision Date

Description The trainer will observe the student's practice and can change the exercise if
it is not suitable

Actors Trainer

Preconditions The trainer must be meticulous in observing and evaluating

Postconditions

Flow Students need to practice for the trainer to make an assessment

Alternative Flows

Exceptions

20
Requirements Trainers must have techniques and focus on observing and evaluating their
students properly

Name of Use Case Create Workout Plans

Created By Group 2 Last Update By Nguyen Minh Duc

Date Created 08/04 Last Revision Date

Description The trainer creates a workout plan to achieve the desired member results

Actors Trainer

Preconditions Technical and scientific elements are a must-have in a trainer

Postconditions

Flow Apply the knowledge of the trainer to give appropriate lessons

Alternative Flows

Exceptions Inappropriate workout plan

Requirements Ask students to practice according to the lesson that has been given

Name of Use Case Members’s Training Results

Created By Group 2 Last Update By Nguyen Minh Duc

Date Created 08/04 Last Revision Date

Description After a period of practice, the student's change has met the initial requirements,
if it is not effective, it is necessary to consider and change the exercises to be
more appropriate.

Actors Trainer

21
Preconditions Students always follow and practice according to the exercises given by the
trainer

Postconditions

Flow After the training period, it is necessary to give the results and evaluate the
status.
Alternative Flows

Exceptions Member does not follow the exercises

Requirements If the exercise doesn't work, the trainer should give you a more suitable
exercise

Name of Use Case View Information of Course

Created By Group 2 Last Update By Nguyen Minh Duc

Date Created 08/04 Last Revision Date

Description Allows users to view the gym's courses so that they can choose a course for
themselves

Actors Member

Preconditions Have learned about gym courses

Postconditions

Flow Refer to the training courses.

Choose the right course


Alternative Flows

Exceptions I have researched very carefully about the gym and its courses before

Requirements

22
Name of Use Case Apply for Membership

Created By Group 2 Last Update By Nguyen Minh Duc

Date Created 08/04 Last Revision Date

Description If you become a new member of the gym, you will need to pay fees.

Actors Member

Preconditions Must have money and excitement

Postconditions

Flow Register new member.

Pay the fees for the courses


Alternative Flows

Exceptions

Requirements Pay the fees and train hard

23
3.3. Class diagram

Figure 16: Class diagram.

Explain:
The first is the Person class, this will be the class that stores the user's information including name,
gender, episode time, phone number and email. this will be the SuperClass of the Member class and the
Trainer class.

24
Coming to the Member class, the purpose of this class is to store the user's information and perform some
exclusive functions of this class. In addition to storing information like SuperClass, it also stores the user's
height, weight, and class information. In class Members will be able to perform a number of functions such
as registering for classes, viewing class information, training plans, performing workouts and reporting
training status.

Next is the Trainer class that can create classes and timetables for people to sign up for. The trainer will
have to come up with a workout and eating plan for the class members. The trainer will also be the one to
guide everyone to practice as well as change the exercises that are not suitable for class members.

Next is the Course class, this class will store the information of class members, training time, trainer.
TrainingPlan class will save exercises, timetables, and information about suitable diets for members.
WorkoutActivity class makes exercises and equipment suitable for everyone.

Finally, the Equipment class will perform the function of managing training equipment as well as the number
and type of equipment.

4. Design Patterns
Design patterns are used to represent some of the best practices adapted by experienced object-
oriented software developers. A design pattern systematically names, motivates, and explains a general
design that addresses a recurring design problem in object-oriented systems. It describes the problem, the
solution when to apply the solution, and its consequences. It also gives implementation hints and examples.

Types of Design Patterns:

• Creational Patterns: These design patterns provide a way to create objects while hiding the creation
logic, rather than instantiating objects directly using a new operator. This gives the program more
flexibility in deciding which objects need to be created for a given use case.

• Structural Patterns: These design patterns concern class and object composition. The concept of
inheritance is used to compose interfaces and define ways to compose objects to obtain new
functionalities.

• Behavioral Patterns: These design patterns are specifically concerned with communication
between objects.

4.1. Creational pattern


Creational design patterns form the foundation of software architecture, focusing on how objects are
created within a codebase. These patterns offer structured approaches to instantiation, ensuring alignment

25
with system requirements. By encapsulating creation logic, developers achieve abstraction, separating
instantiation complexities. Whether through factory methods, builders, or singletons, creational patterns
provide techniques for efficient object creation, promoting modularity and maintainability.

There are five main creational design patterns:


• Abstract Factory
• Factory Method
• Builder
• Singleton
• Prototype

a) Singleton
Definition of Singleton:
A singleton is a type of design pattern that guarantees a class has only one instance and offers a
way to access that instance globally. When managing a shared resource, for example, only one object is
required to coordinate operations throughout the system, this is helpful.

Problem Scenario:

A web application frequently has several configurations that need to be maintained, including
logging levels, API keys, database connection settings, etc. Every component in the program should be able
to access and edit these configurations, and you want to make sure that there is only one instance of the
configuration manager throughout the whole thing.

Solution:

You may make a ConfigurationManager class that handles the configurations for the application by
using the Singleton pattern. To avoid direct instantiation, this class would feature a static method that would
grant access to the configuration manager's sole instance as well as a private constructor. This static function
allows any component that needs to access or alter settings to do so.

Figure 17: Example of Singleton.

26
b) Abstract Factory
Definition of Abstract Factory:

Abstract Factory is a creational design pattern that provides an interface for creating families of
related or dependent objects without specifying their concrete classes. It allows a client to create objects
without needing to know their concrete implementations, promoting loose coupling between the client code
and the created objects.

Problem Scenario:

Let's consider a game development scenario where you have different types of characters (e.g.,
warriors, mages, archers) and each character type has its own set of weapons (e.g., swords, staffs, bows).
As the game evolves, you might need to introduce new types of characters or weapons. However, directly
instantiating specific characters and weapon objects in your game code would lead to tight coupling and
make it hard to extend or maintain.

Solution:

This class diagram effectively addresses the problem by employing the Abstract Factory design
pattern, facilitating loose coupling between client code and created objects. The abstract factory interface
defines methods for creating characters and weapons, while concrete factories implement these methods to
create specific families of related objects, such as warriors, mages, and archers with their respective
weapons. Concrete character and weapon classes provide specific implementations for displaying unique
characteristics, ensuring extensibility, maintainability, and flexibility in introducing new types of characters
or weapons without altering existing client code. Overall, this design promotes scalability and adherence to
object-oriented principles in game development scenarios.

Figure 18: Example of Abstract Factory.

27
c) Prototype
Definition of Prototype:

The Prototype design pattern is a creational pattern that enables the creation of new objects by
copying an existing object, known as the prototype, rather than instantiating them through constructors. This
pattern allows for the creation of new objects with similar properties and behaviors to an existing prototype,
thereby reducing the need for subclassing and promoting flexibility in object creation.

Problem Scenario:

Imagine a scenario in a graphic design application where users can create various shapes, such as
circles, squares, and triangles. Each shape may have different properties, such as size, color, and position.
As the application evolves, users may require the ability to create custom shapes or modify existing ones
dynamically. However, directly instantiating new shape objects or modifying existing ones through
constructors would lead to code duplication and limit flexibility in shape creation.

Solution:

To address this, the Prototype design pattern can be applied effectively. This class diagram
introduces the Prototype pattern, which allows for the creation of new shapes by cloning existing prototypes.
Each shape prototype serves as a blueprint, containing common properties and behaviors shared among all
shapes. When users need to create a new shape or modify an existing one, they can simply clone the
appropriate prototype and customize it as needed. This approach reduces code duplication, promotes
flexibility in shape creation, and enables dynamic modification of shapes at runtime without relying on
constructors or subclassing.

28
Figure 19: Example of Prototype (refactoring.guru)

d) Group scenario
GreenBus company has an application for designing buses for the city, initially, the application was
born only to create diesel-powered buses. Recently, the City People's Committee has developed a plan to
use green energy sources, which many customers know and there is a passenger transport company that
proposes to cooperate, with the vehicle being an Electric Bus. But with the original design of the application
only serving diesel-powered Buses, the program's transmission line is closely tied to the vehicle it is.
Therefore, to serve new customers you need to expand the chain to be able to accommodate them. The
newly created diesel and electric buses will have the same components, that is the number of fan systems,
chassis, speakers, and seats. However, the difference will be in the engine part of the Bus.

• In diesel-powered buses, the engine will be a traditional internal combustion engine and the fuel for
them to operate is oil.

• In electric buses, the engine will be a rechargeable battery system.

29
e) Diagram

Figure 20: Creational design pattern scenario diagram.

Explain:
• The IBus declares the interface, which is common to all objects that can be produced and its
subclasses.

• ElectricBus and DieselPoweredBus are different implementations of the product interface.

• The BusFactory class declares the factory method that returns new product objects. The return type
of this method matches the product interface.

• ElectricBusF and DieselPoweredBusF override base factory method and returns a different type of
bus.

4.2. Structural pattern


Structural design patterns are pivotal in software architecture, focusing on how objects are organized
and connected within a system. These patterns offer structured approaches to defining object relationships
and responsibilities, thereby orchestrating a well-organized and navigable system. By encapsulating
interaction and connectivity logic, developers achieve a higher level of abstraction, isolating structural
complexities from implementation details.

30
There are seven main structural design patterns:

• Adapter

• Bridge

• Composite

• Decorator

• Facade

• Flyweight

• Proxy

a) Bridge
Definition of Bridge:

The Bridge design pattern facilitates decoupling between abstraction and implementation by
separating them into separate hierarchies. This pattern enables changes in one hierarchy without affecting
the other, promoting flexibility and maintainability in software systems.

Problem Scenario:

Imagine a scenario in a multinational company where different teams are responsible for managing
various aspects of a product, such as development, testing, marketing, and customer support. Each team
operates in different locations around the world and uses its own set of tools and processes. However, there
is a need for seamless collaboration and communication between these teams to ensure the success of the
product.

Solution:

The Bridge pattern can be applied to address this challenge by establishing a bridge between the
different teams and their respective tools and processes. Instead of tightly coupling each team's processes
with those of other teams, a bridge interface can be defined to encapsulate the communication and
collaboration protocols. Each team would then implement this bridge interface according to their specific
tools and processes.

31
Figure 21: Example of Bridge.

b) Decorator
Definition of Decorator:

The Decorator design pattern is a structural pattern that allows behavior to be added to individual
objects, dynamically, without affecting the behavior of other objects from the same class. It is used to extend
or modify the functionality of objects at runtime by wrapping them with additional classes, called decorators,
which provide new features or behaviors.

Problem Scenario:

Consider a scenario in a coffee shop application where customers can order various types of coffee,
such as espresso, latte, and cappuccino. Each type of coffee can be customized with additional ingredients,
such as milk, sugar, or whipped cream. However, the application needs to support flexible customization
options without creating a separate class for every possible combination of coffee and ingredients.

Solution:

To address this requirement, the Decorator design pattern can be applied. This class diagram
demonstrates how the Decorator pattern allows for the dynamic addition of extra ingredients to coffee orders
without modifying the base coffee classes. Each coffee type (e.g., Espresso, Latte) serves as a base

32
component, while decorators (e.g., MilkDecorator, SugarDecorator) wrap around these base components,
adding specific functionalities, such as adding milk or sugar.

Figure 22: Example of Decorator.

c) Adapter
Definition of Adapter:

The Adapter design pattern resolves incompatibilities between interfaces by creating an intermediary
that translates requests from one interface into a format that another interface can understand. This pattern
enables integration between systems with different interfaces, promoting interoperability and flexibility in
software architecture.

Problem Scenario:

Imagine a scenario where a company is using a legacy payroll system that generates reports in a
proprietary format. However, the company wants to integrate a new accounting software that requires
reports in a standard CSV format. Without the Adapter pattern, the company would face challenges in
integrating the new software with the legacy payroll system due to the incompatible report formats.

Solution:

The Adapter pattern can be applied to address this challenge by creating an adapter that translates
the proprietary report format generated by the legacy payroll system into the required CSV format expected
by the new accounting software. The adapter acts as a bridge between the two systems, allowing seamless
communication and data exchange.

33
Figure 23: Example of Adapter.

d) Group scenario
DevKey is a start-up software design company. Currently, the company's human resources
department is designing a salary calculation process for employees in the IT department. Because there are
many roles and superiors require to divide the salary according to the employee's level, the employee's salary
will be evaluated according to these two criteria.

• Employee information will be provided and specifically divided by roles: architect, developer, tester.
Each role will have a base salary of $800, $700 and $650/month, respectively.

• Employees will be divided into 4 levels: leader, senior, junior, intern. Depending on the level,
employees will have a corresponding salary coefficient from high to low, which is 2.2, 1.8, 1.4 and
0.5.

• The salary that employees receive will be considered according to their role, level and number of
hours worked.

34
e) Diagram

Figure 24: Structural design pattern scenario diagram.

Explain:
With the requirements stated and after considering the suitability, we will choose the Bridge pattern to
build a program for this problem.

• We will have 3 positions in the company: Architect, Developer and Tester respectively are 3 classes,
each position will have the basic salary of each position passed in Class Position.

• Respectively, there will be 4 classes of Leader, Senior, Junior and Intern, each position will have
corresponding salary for each job level. These positions will all have salary contracts at Class
LevelSalary.

• The salary of the positions will be calculated in Class Salary.

4.3. Behavioral pattern


Behavioral design patterns are essential components of software architecture, focusing on how
objects interact and communicate within a system. These patterns provide structured approaches to
defining object collaboration and responsibilities, ensuring organized and manageable system behavior.
By encapsulating communication and interaction logic, developers achieve a higher level of abstraction,
separating behavioral complexities from implementation details.

There are ten main behavioral design patterns:


• Chain of Responsibility
• Command
35
• Iterator
• Mediator
• Memento
• Observer
• State
• Strategy
• Template Method
• Visitor

a) Observer
Definition of Observer:

Observer is a behavioral design pattern that establishes a one-to-many dependency between objects
so that when one object changes its state, all its dependents are notified and updated automatically. This
pattern enables loosely coupled communication between objects, allowing them to stay synchronized
without having explicit knowledge of each other.

Problem Scenario:

Consider a scenario in a stock trading application where multiple investors are interested in receiving
updates about the price changes of certain stocks. Without the Observer pattern, the application would face
challenges in efficiently notifying all interested parties about price changes without tightly coupling the
investors to the stocks they're interested in.

Solution:

The Observer pattern addresses this problem by introducing a subject interface representing the
entity being observed, in this case, the stocks. The subject maintains a list of observers (investors) and
provides methods for attaching, detaching, and notifying observers. When the price of a stock changes, the
subject notifies all registered observers, triggering them to update their respective displays or take
appropriate actions.

36
Figure 25: Example of Observer.

b) Chain of Responsibility
Definition of Chain of Responsibility:

The Chain of Responsibility design pattern establishes a chain of objects, where each object in the
chain has a chance to handle a request or pass it on to the next object in the chain. This pattern enables
decoupling between the sender of a request and its receiver, allowing multiple objects to handle the request
without the sender needing to know which object will ultimately handle it.

Problem Scenario:

Consider a scenario in a customer support ticketing system where different types of tickets need to
be handled by different departments or individuals. Without the Chain of Responsibility pattern, the system
would face challenges in efficiently routing tickets to the appropriate handlers without tightly coupling the
sender of the ticket to its specific handler.

Solution:

The Chain of Responsibility pattern addresses this problem by creating a chain of handler objects,
each responsible for handling a specific type of ticket. Each handler in the chain has a reference to the next
handler, forming a linked list. When a ticket is received, it is passed through the chain of handlers until one
of them handles it. If a handler cannot handle the ticket, it passes the ticket to the next handler in the chain.

37
Figure 26: Example of Chain of responsibility.

c) Strategy
Definition of Strategy:

The Strategy design pattern is a behavioral pattern that enables selecting an algorithm at runtime
from a family of algorithms. It allows the algorithm to vary independently from the clients that use it.

Problem Scenario:

Sustaining success in the ever-changing retail industry requires meeting the varied requirements and
preferences of customers. Creating an efficient pricing plan that not only optimizes profits but also aligns
with the diverse purchase patterns of various consumer categories is one of the main issues encountered by
retail establishments. Some consumers value convenience, quality, or extra services above all else and are
ready to pay higher costs, while others are extremely price-sensitive and actively seek sales and discounts.

Solution:

The Strategy design pattern may be used to create a flexible pricing system in order to overcome
this difficulty. With the help of this pattern, an algorithm family can be defined, each of which is
encapsulated and replaceable. Different pricing techniques in the context of retail pricing might be included
within distinct classes that each implement a shared interface. The retail establishment may thus choose and
implement the best pricing plan dynamically depending on the traits of each consumer segment.

38
Figure 27: Example of Strategy.

d) Group scenario
To ensure that members at FitnessAlpha gym optimize their workouts, Coach Paul has meticulously
crafted training instructions tailored to the equipment available. The gym manager has temporarily
organized these instructions into three categories: equipment-free exercises, dumbbell exercises, and
exercises utilizing gym equipment. Each category is designed to accommodate varying levels of intensity
and skill.

Firstly, the equipment-free exercises encompass foundational movements that require no additional
equipment. Members can focus solely on completing the designated number of reps. These exercises include
jumping jacks (20 calo), burpees (45 calo), mountain climbers (30 calo), plank (15 calo), and bicycle
crunches (25 calo), each associated with its respective caloric expenditure.

Moving on to exercises utilizing dumbbells, members can enhance their workouts by incorporating weighted
resistance. Squats with dumbbells (30 calo), lunges with dumbbells (25 calo), deadlifts (40 calo), bench
presses (35 calo), and shoulder presses (25 calo) are among the exercises included in this category, with
caloric expenditures specified for each.

Lastly, the gym's versatile equipment allows for a wide array of exercises to be performed with just one
device. Whether it's the treadmill for cardio or the stationary bike for endurance, members have the
flexibility to customize their workouts according to Coach Paul's guidance. For instance, running on the
treadmill for 30 minutes can burn approximately 200-300 calories, while an hour-long session can torch
around 400-600 calories. Similarly, cycling in the gym for 30 minutes can expend roughly 150-250 calories,
and a 60-minute session can result in burning 300-500 calories.

39
e) Diagram

Figure 28: Behavioral design pattern scenario diagram.

Explain:
Utilizing the Strategy design pattern, FitnessAlpha gym has implemented a versatile solution for
managing training instructions. At the core of this design is the TrainingStrategy interface, defining a
method for calculating caloric expenditure based on the number of reps completed. Concrete classes such
as EquipmentFreeTraining, DumbbellTraining, and EquipmentTraining implement this interface, each
encapsulating specific calculation logic tailored to their respective training types. The TrainingInstructions
class orchestrates the selection and utilization of these strategies, maintaining a reference to the current
strategy and providing a method to set it accordingly.

This approach fosters flexibility and extensibility, allowing for seamless addition or modification of
training strategies without altering existing code. By adhering to the principles of encapsulation and
separation of concerns, this design promotes maintainability and scalability, empowering FitnessAlpha
gym to efficiently manage training protocols and adapt to evolving fitness requirements.

5. Design Pattern vs OOP


A design pattern serves as a well-researched solution to a common programming problem. Although
it's frequently associated with object-oriented programming, it isn't limited to that. While you might not
always be active, occasionally you generate brilliant ideas. Developing efficient code right away often
requires considerable experience. Studying Design Patterns helps in crafting software effectively.
Essentially, it's like receiving guidance from seasoned creators, condensed into clear, memorable concepts.
You have a choice: either embrace these patterns and take the lead, or ignore them and repeat past mistakes.

40
These scenarios underscore the value of understanding and applying appropriate design patterns. We've
crafted a diagram specifically for this situation based on prior examples. System planning, thanks to its
speed and simplicity, can save significant time and effort.

6. Conclusion
Upon finishing this piece, I had the opportunity to go over the principles of OOP. I am familiar
with the many UML class diagram types that are utilized in system design and analysis, in addition to the
fundamental OOP concepts of abstraction, polymorphism, inheritance, and encapsulation. To assist you in
better comprehending each design, I provide detailed samples along with an explanation of the idea,
symbolism, and application. In addition, I learned the fundamentals of object-oriented programming and,
when needed, how to illustrate the structure of their code using a UML class diagram. I am already
familiar with several design patterns, and I can give instances of them.

7. Reference
1. Shet, P. (2019). Object Oriented Programming With A Real-World Scenario. [online] Available at:
https://www.c-sharpcorner.com/UploadFile/cda5ba/object-oriented-programming-with-real-world-
scenario/. (Accessed: 29 April 2024)

2. KathleenDollard (n.d.). Object-oriented programming - Visual Basic. [online] learn.microsoft.com.


Available at: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-
guide/concepts/object-oriented-programming. (Accessed: 15 November 2022)

3. Clark, D., 2013. Beginning C# Object-Oriented Programming. 2nd ed. s.l.:Apress

41

You might also like