This exercise earns Merit points in C programming. This exercise presents design patterns, especially the Strategy pattern, APIE rules in objectoriented programming, exception handling, and error handling.
Trang 1ASSIGNMENT 2 FRONT SHEET Qualification BTEC Level 5 HND Diploma in Computing
Unit number and title Unit 20: Advanced Programming
Re-submission Date Date Received 2nd submission
Trang 2 Summative Feedback: Resubmission Feedback:
Grade: Assessor Signature: Date:
Lecturer Signature:
2.1
Trang 3Table of Contents
1 Introduction 7
2 Scenario analysis 7
2.1 Scenario 7
2.2 Diagram 8
3 Implementation 10
3.1 Code 10
3.1.1 Tree Code 11
3.1.2 Product Code 14
3.1.3 Fruit Code 15
3.1.4 Medicine Code 16
3.1.5 Wood Code 17
3.1.6 IHarvestStrategy Code 18
3.1.7 FruitHarvestStrategy Code 19
3.1.8 MedicineHarvestStrategy Code 20
3.1.9 WoodHarvestStrategy Code 21
3.1.10 Main menu Code 22
3.1.11 Plant menu Code 25
3.1.12 Harvest menu Code 27
3.1.13 Growth menu Code 29
3.1.14 Validate Code 31
3.1.15 Main program Code 34
3.2 Program screenshots 35
Trang 43.2.1 Flow 1: Plants and growth trees 35
3.2.2 Flow 2: Plants and harvest trees 42
4 Discussion 50
4.1 Range of similar patterns 50
4.2 Usage of pattern 53
5 Conclusion 54
Trang 5Table of Figures
Figure 1: Tree Class Diagram image 8
Figure 2: Class Library Structure image 10
Figure 3: Console App structure image 11
Figure 4: Tree class code image 12
Figure 5: Tree class constructor image 12
Figure 6: CountTime function image 13
Figure 7: Growing tree methods images 13
Figure 8: GetTreeStatus method image 14
Figure 9: Product abstract class image 14
Figure 10: Fruit class image 15
Figure 11: Medicine class image 16
Figure 12: Wood class image 17
Figure 13: IHarvestStrategy interface image 18
Figure 14: FruitHarvestStrategy class image 19
Figure 15: MedicineHarvestStrategy class image 20
Figure 16: WoodHarvestStrategy class image 21
Figure 17: MainMenu class image 22
Figure 18: MainMenu class methods image 1 23
Figure 19: MainMenu class methods image 2 24
Figure 20: PlantMenu class image 25
Figure 21: PlantMenu methods image 26
Figure 22: HarvestMenu methods class image 27
Figure 23: HarvestMenu methods class image 28
Figure 24: GrowthMenu class image 29
Figure 25: GrowthMenu print menu method image 30
Figure 26: Validate class image 31
Figure 27: InputInterger method image 32
Figure 28: InputDouble method image 33
Trang 6Figure 29: ValidateHarvestAmount method image 34
Figure 30: Program class image 34
Figure 31: Running program Flow 1 image 1 36
Figure 32: Running program Flow 1 image 2 36
Figure 33: Running program Flow 1 image 3 37
Figure 34: Running program Flow 1 image 4 38
Figure 35: Running program Flow 1 image 5 38
Figure 36: Running program Flow 1 image 6 39
Figure 37: Running program Flow 1 image 7 40
Figure 38: Running program Flow 1 image 8 41
Figure 39: Running program Flow 1 image 9 42
Figure 40: Running program Flow 2 image 1 43
Figure 41: Running program Flow 2 image 2 44
Figure 42: Running program Flow 2 image 3 45
Figure 43: Running program Flow 2 image 4 46
Figure 44: Running program Flow 2 image 5 47
Figure 45: Running program Flow 2 image 6 48
Figure 46: Running program Flow 2 image 7 49
Figure 47: Running program Flow 2 image 8 50
Trang 71 Introduction
This Assignment represents a follow-up to our ongoing investigation of Object-Oriented Programming (OOP) and Design Patterns Our objective is to showcase the utility and efficiency of these concepts in software development by selecting a real-life scenario, creating a class based on a relevant class diagram, and exploring various Design Patterns This process is geared towards equipping
us with valuable knowledge and skills that will undoubtedly influence our future pursuits in the realm of software engineering
2 Scenario analysis
2.1 Scenario
A farming family in a small village is preparing for the planting season They have been growing trees for many years, but they have not had a way to take care of and come up with harvesting methods for the trees they grow They heard that there was software on the playstore developed by the development team from GWSoft that could help them monitor their crops, plan irrigation and fertilization, and monitor yields and supply harvesting methods
The family farmer decided to use garden management software provided by GWSoft They look for a software that can meet their needs, such as tracking multiple crops from which to harvest products from the crops
The farmer's family was very satisfied with the software after using it It helps them monitor their crops easily They can irrigate and fertilize more effectively And they can track their productivity in more detail Most importantly, the application offers harvesting methods including:
Fruit harvesting method, medicinal leaf harvesting method and wood harvesting method With the fruit harvesting method, the software will check and harvest the number of fruits on the tree based on the user's wishes When the number of fruits on the branches is not enough for the user to harvest, the software will suggest ways to help the tree grow and grow more fruits The method of harvesting tobacco leaves will be similar to the method of harvesting fruits, however the number of leaves harvested will not exceed a certain threshold because it will make it difficult for the plant to grow if harvested too much much
Trang 8At the same time, the software will give suggestions on how to care for the tree so that it has more leaves, to help farmers harvest later
With the wood harvesting method, the software will provide methods to harvest wood with the best yield When the tree is not tall enough to harvest the correct amount of wood the user desires, the software will also provide care instructions to help the tree grow in height and have more wood
Using the above software has not only helped farmers in managing the plants in their gardens, but it has also helped them harvest products from their crops more effectively
2.2 Diagram
My team used the Strategy pattern to implement this scenario Below is the class diagram of the project:
Figure 1: Tree Class Diagram image
Trang 9Class Tree: This is a basic class with attributes such as fruits, leaves, name, Weight, and HealthStatus ) In this class there are methods such as GetTreeHealth() to get health information, Fertilizing() to fertilize, UpdateTreeStatus() to update the current state of the tree, absorbCO2() to absorb CO2, and Watering() to Sprinklers
Class Fruit, Wood, Medicine classes are considered products of the tree They inherit from an abstract class Product and have methods like use() to use the product Specifically:
• Class Fruit: Has attributes such as taste)
• Class Wood: Has properties such as hardness, color, and makeFurniture() method to create wood furniture
• Class Medicine: Has attributes such as usage, medicineType, and makeProduct() method to produce medicine
Interface IHarvestStrategy: This is part of the Strategy design pattern, allowing my project to define different harvesting strategies for product types There are three specific strategies:
• FruitHarvestStrategy: Fruit harvesting strategy
• WoodHarvestStrategy: Wood harvesting strategy
• MedicineHarvestStrategy: Medicine Harvesting Strategy (Tobacco Leaves)
Each strategy has a Harvest(Tree, amount) method to harvest corresponding to the type of product from the tree A tree can harvest both fruit, wood and leaves
Enum HealthStatus: This is an enumeration that defines the possible health states of the plant such as Good, LackFertilize, LackWater, LackCO2, and Bad
The diagram also has solid arrows from product classes to Product indicating inheritance relationships, and dashed arrows from HarvestStrategy to Product indicating that the harvest strategy uses products
Trang 103 Implementation
3.1 Code
Based on the giving class diagram above, I have created all classes that necessary for the project as shown in the image below:
Figure 2: Class Library Structure image
In the diagram given above, the main class that the program will interact with most is the Tree class On top of that, the class diagram also contains product abstract classes which are implemented by the Fruit class, Medicine class, Wood class Furthermore, the image also shows the harvest strategy interface, which also be implemented by the Fruit harvest strategy, Medicine harvest strategy and Wood harvest strategy The classes have been created in the image based on the attributes and names contained in the diagram class
Trang 11Furthermore, to interact with all the class as in the class library above we use console app which has structure as illustrated in the image
Figure 3: Console App structure image
I separate the program's main menu into four menus, in which the main menu will play the most important role It contains vital information about plants and products and is a bridge linking menus together Each menu has a specific function that serves the purpose corresponding to that menu's name Specifically, the tree growing menu will provide methods to grow trees, more specifically, the method of initializing tree objects For tree growing methods, it will contain functions that help increase the value of the tree And the harvest menu will contain strategies to help users harvest products from previously created trees To prevent input data from being entered incorrectly by the user, we have created a validate class that contains validation methods to prevent the program from encountering errors during use Last but not least is the program class where
it has the main function of the program
3.1.1 Tree Code
The image below illustrates the properties of Tree class, along with the enum HealthStatus as described in the class diagram above
Trang 12Figure 4: Tree class code image
To begin with, the HealthStatus describes multiple health states a tree can have Furthermore, private fields that a tree can store include its name, weight (which can be used to collect wood weight), health status (which indicates how healthy the tree is), and fruit count (which indicates how many fruits the tree has) The Name property has a private setter to guarantee that it
is set only during object initialization, and it has public properties to access these attributes Furthermore, the image also shows the basic constructor of tree class with no required parameters
Figure 5: Tree class constructor image
Trang 13Furthermore, the image above describes a constructor of tree class with some parameters such as fruits, leafs, name, height and healthstatus to assign given data to a newly created tree
Figure 6: CountTime function image
On top of that, the function above as shown by the image describes the CountTime function, which is used as a time limit to increase the practicality of the method since each tree development will take some time in real life
Figure 7: Growing tree methods images
Additionally, the images above are methods simulating growth actions of a tree They update the trees attributes based on the passage of time and print the current tree status using the GetTreeStatus method
Trang 14Figure 8: GetTreeStatus method image
Another method illustrated by the image above is GetTreeStatus, which returns formatted string outlining the characteristics and condition of the tree along with all of its data Based on predetermined criteria, the UpdateTreeStatus method assesses the tree's properties and establishes its health state The relevant HealthStatus enum value is returned Every time it is called, this procedure updates the tree status automatically
3.1.2 Product Code
Figure 9: Product abstract class image
The image above describes the abstract class Product, which is implemented by fruit, medicine and wood class The Product class serves as a blueprint for other classes to inherit from, it contains an abstract method named “Use" The “Use" abstract function is part of the Product class, which acts as a model for other classes to follow The "Use" method needs to be implemented by every class that derives from the product class Although all the subclasses use the same function, each one has a unique implementation that encourages customization and flexibility
Trang 153.1.3 Fruit Code
Figure 10: Fruit class image
The image above describes the Fruit class with its property, constructor and some functions similar to the class diagram In order to be able to utilize the same "Use" method with other product classes, such Medicine and Wood, the fruit class is inherited from the abstract class Product Furthermore, this fruit class possesses unique characteristics that characterize the fruit's taste, such as flavor Every fruit contains additional methods like MakeGift and Consume, and when initialized by default,
it has a sweet flavor By invoking Consume and MakeGift, the overridden use method from the Product class emulates the use
of a fruit Specifically, the MakeGift function prints a message to the console to mimic the use of fruit to create gifts, and the Consume method prints a message to the console to mimic the process of consuming fruit
Trang 163.1.4 Medicine Code
Figure 11: Medicine class image
Similarly, the medicine implements the Use function of Product abstract class and has constructor and property same as described in the class diagram above To indicate the drug kind and usage, the drug class has two attributes: MedicineType and Usage Furthermore, this class provides three constructors that enable the generation of medical objects with various parameter combinations By using the MakeProduct method, the usage method is overridden from the Product class to simulate drug usage The MakeProduct method, in particular, prints the appropriate message on the console while simulating the process of manufacturing medicine from leaves
Trang 173.1.5 Wood Code
Figure 12: Wood class image
The image above illustrates wood class with attribute and function same as mentioned in the class diagram above In order to express the qualities of wood, the Wood class is a subclass of the Product class that has three properties: Hardness, Color, and Quantity In addition, three constructors are offered, enabling the creation of wooden things with various parameter setups Like the Fruit and Medicine classes, the Use function is overridden from the Product class By using the MakeFurniture method, which replicates the usage of wood to create furniture and prints the appropriate message to the console, it mimics the use of wood The Burn technique prints a message to the control panel and mimics building a blaze with wood
Trang 183.1.6 IHarvestStrategy Code
Figure 13: IHarvestStrategy interface image
The code that is provided outlines the architecture of an interface called IHarvestStrategy This interface is intended to act as
a template for a collection of strategies that are designed to capture various harvesting techniques from a tree In particular, the interface declares a single method called Harvest, which must be implemented by every class that implements it
By accepting two parameters, a Tree object representing the arboreal source and a numerical value denoting the desired quantity of the harvest The Harvest method is anticipated to streamline the harvesting process This method's return type is
an array of Product instances, indicating a broad nature that includes a variety of harvestable product kinds This design promotes modularity and flexibility within a larger harvesting system by adhering to the concepts of encapsulation and abstraction
Through the use of this interface, programmers can produce many harvesting strategy implementations, all contained in a concrete class These classes would enable a modular and extensible design by offering particular behaviors for harvesting various product categories
Trang 193.1.7 FruitHarvestStrategy Code
Figure 14: FruitHarvestStrategy class image
The code that is being provided outlines a technique called fruit collecting from a tree Two parameters are needed for this method: a Tree object that represents the fruit's arboreal source and a numerical number that indicates the amount of harvest that is sought
The first algorithm subtracts the desired quantity from the extant count to determine how many fruits are still on the tree after harvest A console message explaining the inadequacy and causing the return of an empty list of Products is displayed if the
"remain" variable has negative value, which indicates that there is not enough fruit in the reservoir On top of that, an internal mechanism called UpdateTreeStatus will update the tree status when the "remain" variable is acceptable Additionally, useful messages are written in the console to document the successful harvest Furthermore, a collection of Fruits that implement the products abstract class are produced by this method The console is used to report on the amount of fruit that has been collected, the number of fruits that are still on the tree, and the tree's current health
Trang 203.1.8 MedicineHarvestStrategy Code
Figure 15: MedicineHarvestStrategy class image
The code that is being shown demonstrates a way for gathering medicinal leaves from a tree called called MedicineHarvestStrategy Two parameters are needed for this method, which includes a Tree object that represents the source
of medicinal leaves and a number that represents the required number of leaves to be collected in grams
Initially, the algorithm calculates the remaining quantity of leafs on the tree after the harvest by subtracting the specified amount with tree leaf weight amount and store it to "remain" variable If the resultant value is negative, denoting an insufficient quantity of leafs, a console message is displayed, signaling the inadequacy and leading to the return of an empty list of Products This signifies that there are not enough leafs in the tree for the intended harvest In contrast, if a satisfactory quantity is available, the tree's leaf count is updated, and its health status is recalculated through the invocation of the UpdateTreeStatus method
A dark yellow foreground enhances the visual appeal of the console output during user interaction Next, logging informational messages on the quantity collected, the number of leaves still on the tree, and the tree's present state of health is done In addition, the process produces a set of Products, that is, instances of the Medicine class, which correspond to the collected medicinal leaves When the method is finished, the console color is returned to its initial state to ensure a consistent display
Trang 213.1.9 WoodHarvestStrategy Code
Figure 16: WoodHarvestStrategy class image
This code implements the IHarvestStrategy interface and describes a wood-harvesting strategy for a tree called WoodHarvestStrategy The "Harvest" technique is in charge of managing the wood harvest process by taking wood from a tree using a quantity of wood expressed in kilograms as the parameters
Similar to the other above-mentioned harvesting techniques, the initial step involves calculating the quantity of wood that remains on the tree after harvesting by subtracting the necessary amount from the weight of the wood inside the tree, and then saving the outcome in the "remain" variable If there is not enough wood, as indicated by a negative "remain" variable, the user is informed by a console message The message advises the user to promote tree development before harvesting The UpdateTreeStatus method is used to update the weight and health status of the tree's wood when there is sufficient available The console output descriptive messages describing the quantity of wood harvested, the weight of wood still on the tree, and the tree's present state of health are logged to the console The method returns a collection of Woods concurrently Every time the loop is repeated inside the procedure, a Wood object is created, which is identified by its color "Brown" and wood type
"Red Oak" To maintain a uniform appearance, the console color is returned to its initial state after the wood harvest process
is finished
Trang 223.1.10 Main menu Code
Figure 17: MainMenu class image
The given code, when used in conjunction with a tree management application, defines a class called MainMenu It plays a key element in coordinating user interactions with the tree management system, which provides an extensive feature set for administering and keeping an eye on a virtual garden of trees The application provides features like planting trees, controlling
Trang 23tree growth, harvesting, checking tree status, cleaning the console, and presenting harvest data It also keeps track of a list of Product instances, or Products
Figure 18: MainMenu class methods image 1
On top of that, users can choose from a menu presented by the MenuOption method until they decide to quit the application The MainMenuSelect function is responsible for interpreting the user's selection and initiating relevant functionalities, such as planting, controlling tree development, and harvesting The PrintMainMenu function uses the ConsoleTable third-party library for formatting in order to present the options on the main menu in a systematic manner
Trang 24Furthermore, the TreeStatusOption method gives an overview of every tree in the garden Which displays details about each tree including its height, health condition, number of fruits, and number of leaves
Figure 19: MainMenu class methods image 2
By clearing the console screen, the ClearConsole function improves the tidiness of the user interface Fruits, woods, and leaves are just a few of the gathered goods that are categorized and quantified using the HarvestResult method, which aggregates and presents the harvest's data
Trang 253.1.11 Plant menu Code
Figure 20: PlantMenu class image
The code that is provided controls the features of planting trees in a tree management system through the PlantMenu class It has ways to ask for user input to generate a new tree, add the tree to a garden, and provide a menu with various tree planting options for users to select from
Trang 26The "InputTree" function asks the user to provide information about the tree, including its name, the quantity of fruits and leaves it has, the weight of its woods, and its overall health Using this data, a new Tree object is instantiated, returned, and utilized the next time a new tree with a certain value has to be created In the other hand, the “QuickPlant” method adds a default tree to the garden without user input, providing a quick option for adding trees
Figure 21: PlantMenu methods image
The PlantOption method is illustrated in the following image, where the user is presented with a menu of planting alternatives and given the option to either plant a new tree or utilize the rapid plant option Using the ConsoleTable library, the PrintMenu function presents the various menu options in an organized manner By providing users with the ability to add new trees to the garden, the PlantMenu class assists users with planting operations An important part of improving the overall functionality
of the tree management system is played by this class
Trang 273.1.12 Harvest menu Code
Figure 22: HarvestMenu methods class image