Tải bản đầy đủ (.pdf) (96 trang)

Assignment 1 1651 Advanced Programming Merit

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (3.11 MB, 96 trang )

ASSIGNMENT 1 FRONT SHEET
Qualification

BTEC Level 5 HND Diploma in Computing

Unit number and title

Unit 20: Advanced Programming

Submission date

8/12/2023

Date Received 1st submission

Re-submission Date

8/12/2023

Date Received 2nd submission

Student Name

Tran Duc Long

Student ID

GCH210562

Class


GCH1106

Assessor name

Lê Việt Bách

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


 Summative Feedback:

 Resubmission Feedback:

2.1


Grade:
Lecturer Signature:

Assessor Signature:

Date:


Table of Contents
1.

Introduction ............................................................................................................................................................................................................ 8

2.

OOP general concepts ............................................................................................................................................................................................ 8
2.1. Define and Structure of object-oriented programming ....................................................................................................................................... 8
2.2. 4 principles of object-oriented programming (APIE) ....................................................................................................................................... 12
Abstraction: Simplifying Complexity .................................................................................................................................................................. 12
Polymorphism: Enhancing Flexibility ................................................................................................................................................................. 14
Inheritance: Streamlining Code Through Hierarchies ......................................................................................................................................... 15
Encapsulation: The Foundation of Data Integrity ................................................................................................................................................ 16
2.3. The SOLID Principles of Object-Oriented Programming ................................................................................................................................ 18

3.

OOP scenario ....................................................................................................................................................................................................... 24
Scenario 3 -trees....................................................................................................................................................................................................... 24
Usecase Diagram ..................................................................................................................................................................................................... 26
Class Diagram .......................................................................................................................................................................................................... 29


4.

Design Patterns .................................................................................................................................................................................................... 31
4.1.

General concepts .......................................................................................................................................................................................... 31

Creational Design Patterns ................................................................................................................................................................................... 31
Structural Design Patterns.................................................................................................................................................................................... 31
Behavioral Design Patterns .................................................................................................................................................................................. 32
4.2.

Creational Design Patterns ........................................................................................................................................................................... 32

Factory Method .................................................................................................................................................................................................... 32
Abstract Factory Method ..................................................................................................................................................................................... 34
Builder.................................................................................................................................................................................................................. 36
Prototype .............................................................................................................................................................................................................. 39


Singleton .............................................................................................................................................................................................................. 41
Creational Pattern Scenario.................................................................................................................................................................................. 43
4.3.

Structural Design Pattern ............................................................................................................................................................................. 46

Adapter................................................................................................................................................................................................................. 46
Bridge................................................................................................................................................................................................................... 48
Composite ............................................................................................................................................................................................................ 51

Decorator.............................................................................................................................................................................................................. 52
Facade .................................................................................................................................................................................................................. 56
Flyweight ............................................................................................................................................................................................................. 58
Proxy .................................................................................................................................................................................................................... 60
Structural pattern scenario ................................................................................................................................................................................... 63
4.4.

Behavior Design Pattern .............................................................................................................................................................................. 65

Chain of responsibility ......................................................................................................................................................................................... 65
Command ............................................................................................................................................................................................................. 67
Iterator .................................................................................................................................................................................................................. 69
Mediator ............................................................................................................................................................................................................... 71
Memento .............................................................................................................................................................................................................. 74
Observer ............................................................................................................................................................................................................... 77
State...................................................................................................................................................................................................................... 79
Strategy ................................................................................................................................................................................................................ 82
Template method ................................................................................................................................................................................................. 84
Visitor .................................................................................................................................................................................................................. 86
Behavior Pattern Scenario:................................................................................................................................................................................... 89
5.

Design Pattern vs OOP ........................................................................................................................................................................................ 91


6.

Conclusion ........................................................................................................................................................................................................... 91

References ................................................................................................................................................................................................................... 93



Table of Figures
Figure 1: OOP example image 9
Figure 2: OOP class diagram example image .............................................................................................................................................................. 10
Figure 3: Abstraction example image .......................................................................................................................................................................... 13
Figure 4: Polymorphism example image ..................................................................................................................................................................... 14
Figure 5: Inheritance example image ........................................................................................................................................................................... 16
Figure 6: Encapsulation example image ...................................................................................................................................................................... 18
Figure 7: SOLID example image ................................................................................................................................................................................. 19
Figure 8: Single Responsibility Principle example ...................................................................................................................................................... 19
Figure 9: Open-Closed Principle example ................................................................................................................................................................... 20
Figure 10: Liskov Substitution Principle example ....................................................................................................................................................... 21
Figure 11: Interface Segregation Principle example .................................................................................................................................................... 22
Figure 12: Dependency Inversion Principle example .................................................................................................................................................. 23
Figure 13: Garden management usecase diagram image ........................................................................................................................................... 26
Figure 14: Garden management class diagram image................................................................................................................................................. 29
Figure 15 Factory method (guru, 2020) ...................................................................................................................................................................... 34
Figure 16: Abstract Factory structure image ............................................................................................................................................................... 35
Figure 17: Builder structure image .............................................................................................................................................................................. 38
Figure 18: Prototype structure image .......................................................................................................................................................................... 40
Figure 19 Singleton (guru, refactoring.guru, 2020) .................................................................................................................................................... 43
Figure 20: Mouse production class diagram image ..................................................................................................................................................... 45
Figure 21 Adapter (guru, refactoring.guru, 2020)....................................................................................................................................................... 48
Figure 22: Bridge structure image (guru, n.d.)............................................................................................................................................................. 50
Figure 23: Composite stucture image (guru, n.d.) ....................................................................................................................................................... 52
Figure 24: Decorator structure image (guru, n.d.) ....................................................................................................................................................... 55
Figure 25 facade (guru, refactoring.guru, 2020) ......................................................................................................................................................... 58
Figure 26: Fly weight structure image (guru, n.d.)....................................................................................................................................................... 59
Figure 27: Proxy structure image (guru, n.d.) .............................................................................................................................................................. 61

Figure 28: Vacation Planner class diagram .................................................................................................................................................................. 63
Figure 29: Chain of responsibility structure image ...................................................................................................................................................... 66
Figure 30: Command structure image ......................................................................................................................................................................... 68


Figure 31 Iterator (guru, refactoring.guru, 2019)........................................................................................................................................................ 71
Figure 32 Intent (guru, refactoring.guru, 2018) .......................................................................................................................................................... 73
Figure 35 memento (guru, refactoring.guru, 2020)..................................................................................................................................................... 77
Figure 36 Observer (guru, refactoring.guru, 2018) ...................................................................................................................................................... 79
Figure 37: State structure image.................................................................................................................................................................................. 81
Figure 38: Strategy structure image ............................................................................................................................................................................ 84
Figure 39: Template structure image........................................................................................................................................................................... 86
Figure 40: Visitor structure image ............................................................................................................................................................................... 88
Figure 41: Cooking plan class diagram image .............................................................................................................................................................. 89


1.

Introduction

This report presents an illustrative scenario to demonstrate the application of object-oriented design and analysis, aiming to explore the
fundamental aspects of the object-oriented programming paradigm (OOP). Through this example, we aim to elucidate various OOP
principles such as abstraction, polymorphism, inheritance, and encapsulation. We have included diagrams and code representations for
each wallet, highlighting their OOP characteristics. Providing a practical example facilitates better understanding. We will also supply
examples and explanations for each type of diagram mentioned earlier. Additionally, we will introduce the concept of design patterns,
categorized into three types: creational, structural, and behavioral. These patterns will be illustrated using diagrams within real-world
scenarios, with discussions on how to implement them using UML classes and C# programming techniques.

2.


OOP general concepts
2.1. Define and Structure of object-oriented programming
a. define
Object-oriented programming (OOP) can be easily understood as creating a digital representation of a real-world object.
This approach allows users to interact with the program as if they are dealing with an actual object. OOP has become a
prevalent method in programming, though it's not always necessary as many programs can still be developed without it.
The key benefit of OOP lies in its code organization, which becomes increasingly vital as the project size and complexity
grow. OOP mandates thorough planning before coding begins, ensuring that the code adheres to a predefined structure
from start to end. This organized approach greatly simplifies the process of locating and resolving errors in the code.
(geeksforgeeks, 2023)


Figure 1: OOP example image

This provided example demonstrates the use of Object-Oriented Programming (OOP) to create a model of a dog. In this
model, the 'Dog' class acts as a blueprint for depicting a dog. This class is responsible for defining various aspects of a
dog, including its shape, size, name, age, and behaviors, which are displayed in the main program.
The model illustrated consists of four key components: class, object, attribute, and method. In this context, the 'Dog' class
represents a generic category of dogs, encompassing various breeds like Alaska, Belarus, Dogo, etc. This class is
equipped with specific attributes such as weight, height, and preferred food, which characterize a dog. Additionally, it
outlines common actions like running, playing, and eating that all dogs are capable of. Each individual dog is an object
of the 'Dog' class, identifiable by unique attributes like its name. While the 'Dog' class is a broad category, the specific
properties, methods, and objects within it allow for the differentiation of each unique dog within the larger class. This


approach showcases how OOP can be used to organize and represent complex entities in a structured and understandable
manner.

Figure 2: OOP class diagram example image


b. Class
In object-oriented programming (OOP), a class functions as a template for constructing objects, and each class is
designed with a distinct purpose to describe a particular object. Users create custom objects by employing the 'class'
keyword for their definition. A class essentially encapsulates a predefined set of plans, detailing how objects should be
structured and behave. Within a class, users define various components like attributes, objects, and methods.
(geeksforgeeks, 2023)
Referring to the earlier dog example, the class represents the framework for creating a dog's representation. This class
lays out all the specific details of the dog, such as its characteristics and behaviors. Attributes, objects, and methods
unique to the dog are all intricately defined within the class, providing a comprehensive and organized way to represent


the dog in a programming context. This exemplifies how classes in OOP serve as foundational structures that outline
the specifics of what they represent.
c. Object
An object is a fundamental concept to consider when creating your program. It represents entities that hold values and
perform tasks within a computer system. Objects can belong to a common class, and many such classes are employed
to define reusable components in code. Each object is either an instance of a subclass or an entire class, and each object
possesses its own set of methods, procedures, and data types. (geeksforgeeks, 2023)
All private objects share three essential characteristics:
Identity: Each object has a unique identifier that distinguishes it from all others.
State: This refers to the properties or attributes of an object.
Behavior: It signifies the actions or functions that an object can carry out.
Objects can be used to define various things, such as data structures, functions, and methods. For instance, in the
example of a dog, an object could be created to represent the dog itself, and additional objects like the dog's name and
age can be utilized to make it easier to identify and work with the dog.
d. Attributes
Properties reside within classes or objects and can manifest as distinct qualities in layers or objects. An attribute can be
thought of as a trait inherent to the class that houses it. Attributes enable classes to interact with other objects and
differentiate them from one another. (geeksforgeeks, 2023)
In the context of the previously mentioned dog description example, attributes represent specific characteristics of the

dog, such as its weight, height, and preferred food. These attributes serve as unique identifiers for each dog, allowing
users to differentiate between individual dogs, as not all dogs share the same characteristics.
e. Method
A method is quite similar to a function in that it can yield a result based on the type of data initially defined for that
method. It resembles a function in procedural programming as well. Methods can accept input values, carry out
instructions, and produce outcomes, much like functions. However, the distinction lies in how methods are categorized
based on the objectives of the class they belong to. Methods operate within the context of classes. (geeksforgeeks,
2023)


Illustrating this with the example of a dog, consider methods like "Run()," "Play()," and "Eat()." These methods are
designed to enforce specific actions related to a dog's running, playing, and eating behaviors. When invoked, these
methods can modify the attributes associated with the corresponding activities of the dog.
f. Constructor
In object-oriented programming, a constructor is a specific method within a class or structure that initializes a newly
created object of that type. The constructor is automatically called whenever an object is instantiated. It allows for the
assignment of values to the members of an object, either through default values or values provided by the user. A
constructor is similar in concept to an instance method and typically shares the same name as the class it belongs to.
However, it's important to note that the constructor differs in that it lacks a defined return type. When used without any
parameters, the constructor sets the object's members to their default values, and when parameters are provided, they
are directly used to initialize the object's attributes. (geeksforgeeks, 2023)
As an illustration, let's consider an object called "Dog" that includes two constructors. The default constructor, "Dog(),"
does not possess information about the dog's name, while the constructor with a parameter, "Dog(string name)," takes
in the dog's name as a string parameter. This means that when creating an instance of the "Dog" object, you can provide
a name for the dog as an argument to this constructor. Furthermore, it's possible to create a constructor that
accommodates multiple parameters, each carrying values like weight and height. For instance, you could have a
constructor like "Dog(string name, double height, double weight)," where you provide the name, height, and weight of
the dog when initializing the object.

2.2. 4 principles of object-oriented programming (APIE)

Abstraction: Simplifying Complexity
Abstraction in OOP is about focusing on essential aspects while ignoring the specifics. It's used to create simple models
representing more complex underlying code structures. Abstraction is realized through interfaces or abstract classes.
For example, an abstract PaymentProcessor class could define a method processPayment() without specifying how the
payment processing is done. Classes like CreditCardProcessor and PayPalProcessor would then extend this abstract class and


provide specific implementations for processPayment(). This abstraction allows users of these classes to utilize different
payment methods without understanding the underlying complexities. (Monus, 2023)

Figure 3: Abstraction example image

In this diagram:
● The PaymentProcessor class is an abstract class, indicated by the <<abstract>> keyword. It defines the method
+processPayment(): void without implementing it.
● The CreditCardProcessor class extends the PaymentProcessor class, providing a specific implementation of the
processPayment() method.


● The PayPalProcessor class also extends PaymentProcessor, with its own implementation of processPayment().
● The arrows from CreditCardProcessor and PayPalProcessor to PaymentProcessor indicate that they are subclasses,
inheriting the abstract method and providing concrete implementations.
Polymorphism: Enhancing Flexibility
Polymorphism, literally meaning 'many forms,' allows objects of different classes to be treated as objects of a common super
class. This is particularly useful for creating flexible and scalable code, where the exact type of object might not be known and
different behaviors are expected.
A classic example is a Shape interface with a method draw(). Various classes like Circle, Square, and Triangle implement this
interface and provide specific implementations for draw(). When a program calls the draw() method on a collection of Shape
objects, each object's specific draw() method is executed, illustrating polymorphism. (Monus, 2023)


Figure 4: Polymorphism example image

In this diagram:
● The PaymentMethod interface is defined with the method +pay(amount: Double): String.
● The classes CreditCard, DebitCard, and PayPal implement the PaymentMethod interface, each providing a specific
implementation of the pay method.


● The dotted arrows from CreditCard, DebitCard, and PayPal to PaymentMethod indicate that these classes implement
the PaymentMethod interface. This illustrates polymorphism, where objects of these classes can be treated as objects of
the PaymentMethod type.
● When the pay method is called on a collection of PaymentMethod objects, the specific pay method of each object
(CreditCard, DebitCard, PayPal) is executed, showcasing polymorphism in action.
Inheritance: Streamlining Code Through Hierarchies
Inheritance is about creating new classes from existing ones, inheriting attributes and methods. It's instrumental in reducing
redundancy and enhancing code reuse. This principle lets you build a hierarchy of classes that encapsulates shared
characteristics in a base class, and specialize or extend in derived classes.
Consider a basic Vehicle class with properties like speed and fuelCapacity. From this, you can derive specialized classes like
Car and Truck, which inherit common features from Vehicle but also introduce unique attributes like seatingCapacity for Car
and cargoCapacity for Truck. This setup avoids duplication and facilitates maintenance. (Monus, 2023)


Figure 5: Inheritance example image

In this diagram:






The Vehicle class is the base class with attributes -speed: Double and -fuelCapacity: Double.
The Car class, derived from Vehicle, adds a unique attribute -seatingCapacity: Int.
The Truck class, another subclass of Vehicle, introduces its own attribute -cargoCapacity: Double.
The inheritance is represented by arrows pointing from Car and Truck to Vehicle, indicating that they inherit the
properties and methods of the Vehicle class.

Encapsulation: The Foundation of Data Integrity
Encapsulation serves as a means of safeguarding data to prevent unauthorized access by others. For instance, when I wish to
share something on Facebook, I can choose to make it visible to the public, restrict it to only my friends, or keep it entirely
private, inaccessible to anyone else.


In the context of Object-Oriented Programming (OOP), encapsulation can also pertain to restricting direct access to specific
parts of an object, preventing users from obtaining the internal state values of all the object's variables. As a result, data
members and functions associated with an instantiated class or object can be concealed through encapsulation. Think of
encapsulation as a capsule, where the rigid outer shell represents the class, and the contents inside, including data and methods,
are kept secure. (Monus, 2023)
Access modifier in encapsulation is divided into 4 types such as public, private, protected and no modifier. Each type will have
the following uses:
● Public: Members marked as public are accessible from anywhere in the program, both within and outside the class or
component.
● Private: Members marked as private are only accessible within the class or component where they are defined. They are
not accessible from outside the class.
● Protected: Members marked as protected are accessible within the class where they are defined and in any subclasses or
derived classes. They are not accessible from outside the class hierarchy.
● Default (No Modifier): When no access modifier is specified, the default visibility is typically limited to the package or
module in which the class or component resides. It restricts access from outside the package or module.
Here is a straightforward real-life illustration of encapsulation: A boy's personal information is only accessible to those who
are very close to his . For instance, his girlfriend has access to details such as his phone number, name, and bank account.
Strangers are only aware of his name, while neighbors are only aware of his phone number.



Figure 6: Encapsulation example image

By integrating these principles into your OOP practices, you're not just adhering to the APIE acronym; you're embracing a
comprehensive approach that enhances code quality, scalability, and maintainability. These concepts are the pillars upon which
robust and efficient object-oriented systems are built.

2.3. The SOLID Principles of Object-Oriented Programming
In the realm of Object-Oriented Programming (OOP), SOLID represents an acronym coined by Michael Feathers. It encapsulates
five design principles employed to enhance the comprehensibility, adaptability, and ease of maintenance in software design. It's
worth noting that these principles constitute just a portion of the broader set of design principles advocated by Robert C. Martin.


Figure 7: SOLID example image

● Single Responsibility Principle:
One class should only have one responsibility and only change its for one reason. For example: in the image below describe
one class handle two thing at a time, including handle input data and analysis data. This example violate the Single
Responsibility Principle. If we change how data input in GetInputData, we will also need to change the AnalysisData.
(authoranuupadhyay, 2022)

Figure 8: Single Responsibility Principle example

● Open-Closed Principle:
A class is always expandable if needed, but to do so we should not directly change the main class. Instead we should create a
new class to extend the old class by using inherit or so. (authoranuupadhyay, 2022)


Figure 9: Open-Closed Principle example


● Liskov Substitution Principle:
The principle was introduced by Barbara Liskov in 1987 and according to this principle “Derived or child classes must be
substitutable for their base or parent classes“. This principle ensures that any class that is the child of a parent class should be
usable in place of its parent without any unexpected behavior. (authoranuupadhyay, 2022)



×