1. Trang chủ
  2. » Công Nghệ Thông Tin

ASM 1 Advanced Programming 1651FPT Greenwich (Full Distinction criteria) (new 2022))

44 39 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 44
Dung lượng 3,82 MB

Nội dung

Điểm của bài asm còn tùy thuộc vào người chấm. Chỉ cần paraphase bài này là có thể đạt merit hoặc có thể đạt distinction tùy vào thầy dạy. 1 trong nhưng tool paraphase mình recommend là quillbot.ASSIGNMENT 1 FRONT SHEET Qualification BTEC Level 5 HND Diploma in Computing Unit number and title Unit 20 Advanced Programming Submission date Date Received 1st submission Re submission Date Date Rec. ASSIGNMENT FRONT SHEET Qualification BTEC Level HND Diploma in Computing Unit number and title Unit 20: Advanced Programming Submission date Date Received 1st submission Resubmission Date Date Received 2nd submission Student Name Student ID Class Assessor name 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: Grade: Lecturer Signature:  Resubmission Feedback: Assessor Signature: Date: Table of Contents A INTRODUCTION B OOP GENERAL CONCEPT a) WHAT IS OOP OOP Introduction General Concept of OOP Object and Class in OOP Pros and Cons of OOP b) APIE Inheritance Abstraction 10 Encapsulation 10 Polymorphism 11 c) SOLID 11 S Singleresponsibility Principle 11 O Openclosed Principle 12 L Liskov Substitution Principle 12 I Interface Segregation Principle 12 D Dependency Inversion Principle 12 C OOP SCENARIO 12 3.1 Scenario 12 3.2 Use case Diagram 14 3.3 Class Diagram 19 D Design Patterns 21 Importance of Design Pattern: 21 When to use Design Patterns: 21 4.1 Creational pattern 22 Description of a creational scenario 26 4.2 Structural pattern 28 Description of a structural scenario 32 4.3 Behavioral pattern 34 Description of a behavioral scenario 43 E Design Pattern vs OOP 45 F Conclusion 46 References 46 List Of Tables Table 1: StartGame Usecase 15 Table 2: PlayGame use case 16 Table 3: Change Setting Usecase 17 Table 4: View Records usecase 17 Table 5: Exit Usecase 18 Table 6: Ingame menu usecase 19 List Of Figures Figure 1: OOP Introduction Figure 2: OOP Concept Figure 3: Inheritance Example Figure 4: Abstraction Example 10 Figure 5: Encapsulation Example 11 Figure 6: Polymorphism Example 11 Figure 7: Usecase for Scenario 14 Figure 8: Class Diagram for scenario 19 Figure 9: Apstract Factory 23 Figure 10: Factory Method 24 Figure 11: Builder Pattern 24 Figure 12: Prototype Pattern 25 Figure 13: Singleton Design Pattern 26 Figure 14: Class diagram of creational scenario 27 Figure 15: Adapter Pattern 28 Figure 16: Brigde Pattern 29 Figure 17: Composite Design pattern 29 Figure 18: Decorator Design Pattern 30 Figure 19: Facade Design pattern 31 Figure 20: Flyweight Design Pattern 31 Figure 21: Proxy Design pattern 32 Figure 22: Class diagram of structural Scenario 33 Figure 23: Chain of Responsibility 34 Figure 24: Command Design pattern 35 Figure 25: Interpreter Pattern 36 Figure 26: Iterator Design Pattern 37 Figure 27: Mediator Pattern 38 Figure 28: Memento Design Pattern 38 Figure 29:Observer Design Pattern 39 Figure 30: State Design Pattern 40 Figure 31: Strategy Design pattern 41 Figure 32: Template Method design pattern 42 Figure 33: Visitor Design Pattern 43 Figure 34: Class Diagram of Behavioral Scenario 44 A INTRODUCTION A design pattern is a reusable solution for common problems in software design with a specific circumstance A design pattern is a blueprint that cannot be converted into source code Typically, objectoriented design patterns depict relationships and interactions between classes or objects but not specify the classes or objects involved in the final application This is a report about objectoriented paradigms and design patterns First, we will learn about OOP and the general concepts of OOP Next, we will analyze in detail a situation related to OOP Design patterns will be introduced and analyzed its general concepts The article will compare and analyze the relationship between objectoriented paradigms and design patterns Finally, we will design and build class diagrams using a UML tool B OOP GENERAL CONCEPT a) WHAT IS OOP OOP Introduction Figure 1: OOP Introduction With the launch of Simula in the mid1960s, OOP principles initially appeared, and they expanded further in the 1970s with the introduction of Smalltalk Objectoriented methods evolved even though software developers did not adopt early breakthroughs in OOP languages In the mid1980s, there was a resurgence of interest in objectoriented methods OOP languages, C++, and Eiffel have grown popular among mainstream computer programmers Throughout the 1990s, OOP increased in prominence, most notably with the launch of Java and the enormous following it acquired Furthermore, in 2002, in conjunction with the release of the NET Framework, Microsoft launched C (pronounced Csharp), a new OOP language, and a redesign of their hugely popular existing language, Visual Basic, to make it fully objectoriented OOP languages are still popular today and play a significant role in contemporary programming (Alexander S Sarah Lewis, 2017) General Concept of OOP Figure 2: OOP Concept Objectoriented programming is a way of creating software in which the structure is built on objects interacting with one another to achieve a goal As part of this interaction, messages are sent between the objects An object can act in response to a message OOP is a programming technique that allows programmers to create objects in code that abstracts reallife objects This approach is now successful and has become one of the paradigms for software development, especially for enterprise software During the development of OOP applications, classes will be defined to model actual objects These classes will be executed as objects When users run the application, the methods of the object will be called The class defines what the object will look like: what methods and properties will be included An object is just an instance of the class Classes interact with each other by the public API: a set of methods, and its public properties The goal of OOP is to optimize source code management, increase reusability, and most importantly, help encapsulate procedures with known properties using objects (Alexander S Sarah Lewis, 2017) Object and Class in OOP 3.1 Class In OOP, a class is frequently understood as a blueprint for creating objects (a specific data structure), providing initial values and constructors for the nature (instance variables or attributes), and defining and implementing behaviour (member functions or methods) Classes are used to generate and manage new objects, as well as to facilitate inheritance, which is a crucial component of objectoriented programming and a technique for code reuse (Oracle, 2012) 3.2 Object A class instance is an object In OOPS, an object is a selfcontained component with methods and attributes that make a specific type of data usable An object in OOPS might include a data structure, a variable, or a function from a programming standpoint It has a memory area set aside for it Pros and Cons of OOP 4.1 Pros      OOP models complex things as simple structures Reusable OOP code, which saves resources It makes debugging easier Compared to finding errors in many places in the code, finding errors in (prestructured) classes are more straightforward and less timeconsuming High security, protecting information through packaging Ease of project expansion 4.2 Cons    Make data processing separate When the data structure changes, the algorithm must be modified OOP does not auto initialize and release dynamic data, and it does not accurately describe the actual system b) APIE Inheritance In OOP, inheritance is used to classify objects in your programs based on shared characteristics and functions Working with objects becomes more accessible and more intuitive as a result It also facilitates programming by allowing you to combine typical characteristics into a parent object and inherit these characteristics in child objects (Alexander S Sarah Lewis, 2017) This is a feature commonly used in software development Inheritance allows creating a new class (Child class), inheriting, and using properties and methods based on the parent class The Child classes inherit all the Parent class components Subclasses can extend the components or add new ones (Nitendratech, 2018) Example: There are many types of vehicles In this case, the Vehicle can be considered as the base class with properties color, wheel, engine, weight and actions Start, Stop, Turn “Car” and “Motorbike” are two derived classes that inherited from the base class Both classes inherit all attributes and actions from the base class but “Car” also contains action Reverse and “Motorbike” contains action kickstand Figure 3: Inheritance Example Guns will increase plane damage     Light gun: + damage (free) Standard gun: + damage (50000 points) Heavy gun: + damage (200000 points) Legendary gun: + damage (1000000 points) Engine will increase plane speed    Standard engine: + 10 speed (free) Double engine: + 20 speed (100000 points) Space engine: + 30 speed (500000 points) Support plane: Depending on the type of aircraft supporting it, it will have different functions   Trinity: increase health, damage and 30 speed for player main plane when active (5000000 points) Blood thirster: heal health after taking down an enemy heavy aircraft when active (5000000 points) Figure 22: Class diagram of structural Scenario Explanation The base Plane Abstract class defines properties, methods for the subclass as well as some methods (GetDecription, ) that these concrete decorators can alter These concrete classes (Conqueror, Flash, Sky Doom) provide these default implementations of the properties and methods The PlaneDecorator class extends the Plane class as the other components The primary intent of this class is to clarify the wrapping for all concrete decorators (Lightgun, HeavyGun, Light Amor) The default implementation of the wrapping code includes the _plane (DataType: Plane) property for storing a wrapped plane and the means to declare it The _plane variable should be accessible to the sub decorator classes, so its necessary to make this variable with the protected access modifier This class also delegates work to concrete decorator classes These concrete decorator classes (Lightgun, HeavyGun, Light Amor ) extendthe base decorator functionality and modifying the component behavior accordingly of the plane Decorator class 4.3 Behavioral pattern These design patterns are all about Classs object communication Behavioral patterns are those patterns that are most specifically concerned with communication between objects Behavioral Pattern Include:  Chain of responsibility: A way of passing a request between a chain of objects Sender transmits a request to a chain of objects in chain of responsibility Any item in the chain can handle the request Avoid tying the sender of a request to its recipient by giving different objects a chance to handle the request, according to the Chain of Responsibility Pattern In the process of dispensing money, an ATM, for example, employs the Chain of Responsibility design pattern (sourcemaking, n.d.) Figure 23: Chain of Responsibility ImageCre: Chain of responsibility design pattern RefactoringGuru To put it another way, each receiver generally contains a reference to another receiver If one object is unable to process the request, it is sent to the next recipient, and so on Advantage of Chain of Responsibility Pattern    It decreases coupling While assigning duties to objects, it offers flexibility It lets a group of classes function as if they were one; events generated by one class may be passed to other handler classes via composition Usage of Chain of Responsibility Pattern:   When a request can be handled by more than one object and the handler is uncertain When a group of objects capable of handling a request must be dynamically provided  Command: Encapsulate a command request as an object According to the Command Pattern, Encapsulate a request in an object and deliver it to the invoker object as a command The invoker object searches for a relevant object that can handle this command and passes the command to that object, which then performs the command Figure 24: Command Design pattern ImageCre: Command Design Pattern Stackoverflow Advantage of command pattern:   It distinguishes between the object that executes the action and the object that invokes it Because current classes arent modified, its simple to add new commands Usage of command pattern:    When you need to parameterize, objects based on an action When many requests must be created and executed at separate times When rollback, logging, or transaction functionality is required  Interpreter: A way to include language elements in a program To define a representation of grammar of a particular language, as well as an interpreter that uses this representation to interpret sentences in the language, according to an Interpreter Pattern In general, the Interpreter pattern can only be used in a restricted number of situations The Interpreter pattern can only be discussed in terms of formal grammar, although there are superior solutions in this field, which is why it is not often utilized Figure 25: Interpreter Pattern ImageCre: Interpreter Pattern Baeldung Advantage of Interpreter Pattern   It is less difficult to modify and expand the grammar Its simple to put the grammar into practice (sourcemaking, n.d.)  Iterator: Sequentially access the elements of a collection Provide a method for progressively accessing the constituents of an aggregate object without revealing its underlying representation The traversal of a collection should be elevated to full object status. traverse with polymorphism Figure 26: Iterator Design Pattern ImageCre: Iterator Pattern RefactoringGuru Advantage of Iterator Pattern   It allows you to traverse a collection in different ways It streamlines the collections user interface Usage of Iterator Pattern:   When you need to get a hold of a group of things without revealing their internal representation When many traversals of items are required, the collection must be able to accommodate them  Mediator: Defines simplified communication between classes To define an entity that captures how a group of objects communicate, states the Mediator Pattern Ill demonstrate the Mediator pattern by examining an issue When we first start developing, we have a few classes that interact with one another to produce outcomes Consider how, as functionality develops, the reasoning becomes more complicated So, what happens next? We added additional classes, and they still communicate, but maintaining this code is becoming increasingly tough As a result, the Mediator pattern solves this issue (sourcemaking, n.d.) Figure 27: Mediator Pattern ImageCre: Mediator Pattern DotNetTutorials The mediator pattern is intended to simplify communication across various objects or classes This technique creates a mediator class that generally handles all communication between distinct classes and makes the code easier to maintain Memento: Capture and restore an objects internal state To restore the state of an item to its prior state, according to a Memento Pattern However, it must so without breaking Encapsulation In the event of a mistake or failure, such a scenario is beneficial Token is another name for the Memento pattern Figure 28: Memento Design Pattern ImageCre: Memento Desine Pattern RefactoringGUru One of the most often used operations in an editor is undo, sometimes known as backspace or ctrl+z The undo action is implemented using the Memento design pattern This is accomplished by storing the objects current state as it changes  Observer: A way of notifying change to a number of classes Just construct a onetoone dependence so that when one object changes state, all its dependents are alerted and changed immediately, according to the Observer Pattern Dependents or PublishSubscribe are other names for the observer design Figure 29:Observer Design Pattern ImageCre: Observer DesignPattern SourceMaking Benefits:   It explains the interaction between the observer and the objects It allows for broadcaststyle communication to be supported Usage:   When a state changes in one item must be mirrored in another without the objects being tightly connected When we design a framework that will be updated in the future with additional observers with few changes (sourcemaking, n.d.)  State: Alter an objects behavior when its state changes The class behavior changes dependent on its state, according to a State Pattern We generate objects that represent distinct states and a context object whose behavior changes as its state object changes in State Pattern Objects for States is another name for the State Pattern Figure 30: State Design Pattern ImageCre: State Design Pattern Advantages:   It preserves statespecific behavior Any state transitions are made explicit Usage:   When an objects behavior is dependent on its state and it has to be able to adjust its behavior at runtime to match the new state Its utilized when there are a lot of multipart conditional statements in the actions that are dependent on the state of an object  Strategy: Encapsulates an algorithm inside a class Defines a family of functions, encapsulates each one, and makes them interchangeable, according to a Strategy Pattern Policy is another name for the Strategy Pattern Figure 31: Strategy Design pattern ImageCre: Strategy Design Pattern Sourcemaking Benefits:    It may be used instead of subclassing Each behavior is defined within its own class, removing the need for conditional expressions It makes it easy to add new functionality without having to rewrite the program Usage:   When many classes differ simply in their behaviors, this is used When multiple variants of an algorithm are required, it is utilized  Template method: Defer the exact steps of an algorithm to a subclass In an operation, define the skeleton of an algorithm while deferring some stages to client subclasses Subclasses can rewrite some phases of an algorithm using the Template Method without affecting the algorithms structure Figure 32: Template Method design pattern ImageCre: Template Method Source Making Algorithm placeholders are declared in the base class, and the placeholders are implemented in the descendant classes Strategy is similar to Template Method in terms of granularity Inheritance is used in the Template Method to alter parts of an algorithm Delegation is used in strategy to change the whole algorithm Individual objects logic is altered by strategy The Template Method affects the entire logic of a class Template Method is a subset of Factory Method (Anon., 2022)  Visitor: Defines a new operation to a class without change Represent an operation that will be executed on an object structures components Without modifying the classes of the components on which it acts, Visitor allows you to specify a new operation The traditional method for restoring type information that has been lost, Figure 33: Visitor Design Pattern ImageCre: Visitor Pattern SourceMaking Based on the two types of items, take the appropriate action Interpreters abstract syntax tree is a Composite (therefore Iterator and Visitor are also applicable) A Composite can be traversed by an Iterator Over a Composite, a visitor can perform an operation Because the visitor can begin whatever is suitable for the type of item it meets, the Visitor pattern is similar to a more powerful Command pattern (Javatpoint, n.d.) Description of a behavioral scenario In Greenwich, while the current semester isnt finished yet, students will immediately receive notification of paying tuition fees for the next semester Tuition Fees could be paid online via various emoney transfer platforms: VieettelPay, DNG bankDebit card, and TPbank Students can check the transaction cost of the payment via the payment tuition fee online With paying via Viettel Pay, go to Viettel Pay App, verify the Viettel phone number and Select FPT tuition payment Enter student code and perform pay the tuition fee The transaction fee of Viettel pay is free With DNGbank, the necessary info is the information on the bank card (Name, card number, Expired date) The DNGBank’s transaction fee is 3300 vnd The other is the DNGDebit payment method, its necessary info also the information on the Debit Card (Name, Card number, CVV and expired date) The transaction of this payment method is 1,4% of the tuition fee + 3300 vnd Figure 34: Class Diagram of Behavioral Scenario Explanation: The GWPayingTuitionFeeOnline accepts IPayingTuitionFeeStrategy object through the constructor The GWPayingTuitionFeeonline does not know the concrete classes of this strategy But It could work with all strategy classes through the IPayingTuitionFeeStrategy interface IPayingTuitionFeeStrategy Interface for strategy pattern in this case to pay tuition fee, the student object passed as an argument These concrete classes implement the IPayingTuitionFeeStrategy Interface to implement algorithms for paying tuition fees using DNGdebit, DNGbank or via Viettelpay Concrete Strategies (ViettelPayStrategy, DNGBankStrategy, DNGDebitStrategy) implement the algorithm while implementing the IPayingTuitionFeeStrategy interface This interface helps these concrete strategy classes interchangeably This solution delegates the selection of payment method to the Strategy object instead of implementing multiple versions of the algorithm on its own The selection of the algorithm defined by these concrete strategy classes will be called via the IPayingTuitionFeeStrategy interface E Design Pattern vs OOP The concepts of OOP provide design patterns, which assist to build OOP more effectively and adapt to scenarios It will take much longer to run the program or address difficulties if you dont use a design pattern Design patterns can make your code more reusable and adaptable, allowing you to include any function that fulfills the criterion (Techopedia, 2011) For example, when a car is created, there are only doors, engine, wheels But what will happen when owners take their car to a modification garage to add more features (body kit, spoiler, sticker) The simplest way to solve that problem is extend the base class and create a bunch of subclasses or create a massive constructor with lots of unused parameters In this case, the builder design pattern helps the user to execute these steps of the builder You can create various builder classes with the same set of builder steps set but in a different manner Another example that can be applied is vehicle painting The simplest way is creating a Vehicle class and pairs of subclasses such as Car and Motorbike To create colored vehicles in red and green, users need to create a bunch of subclasses such as GreenCar, RedCar, GreenMotorbike, RedMotorbike Problems will occur if users decide to add a few more colors By switching from inheritance to object composition, the Bridge pattern tries to tackle this problem The colorrelated code can be extracted into its own class with two subclasses: Red and Green The Vehicle class then receives a reference field that points to one of the color objects Any colorrelated tasks can now be delegated to the connected color object by the shape This reference will serve as a bridge Design pattern is not a design that can be transferred directly into code, it Is only a description of way to solve many problems in many situations Even without the specification of class and object, design pattern illustrates the relationship of classes on objects and how they interact Theres always occurs problem when programming and various ways to solve it, but it maybe not be optimal choice Design patterns are created to handle an issue in the most efficient way possible, with solutions available in OOP programming and most modern programming languages F Conclusion The report covered ideas and features of ObjectOriented Programming (OOP), as well as how to apply OOP in practice with considerable scripting Explain the systems activities and behavior for the scenario described in the research using two use case diagrams (use case diagram, class diagram) We may learn the foundations of OOP and its concept through this report Weve also detailed the general definitions and features of three different types of design patterns: structural, creational, and behavioral patterns Each one includes a class diagram, activity, and explanation to show how design patterns and OOP are related This can assist us improve our programming language approach and make our project run more smoothly This report can also serve as a foundation for future reports References Alexander S Sarah Lewis, 2017 objectoriented programming (OOP) Online Available at: https:www.techtarget.comsearchapparchitecturedefinitionobjectorientedprogrammingOOP Anon., 2022 Refactoring.Guru Online Available at: https:refactoring.gurudesignpatterns Anon., n.d Online Available at: https:topdev.vnblogsolidlagi?fbclid=IwAR2UzzITTxPd3eXG7b4kpG40kJYj3pMs_kSnYo30wjPlMlo61F8A4pveS80:~:text=L%E 1%BA%ADp%20tr%C3%ACnh%20h%C6%B0%E1%BB%9Bng%20%C4%91%E1%BB%91i%20t%C6 %B0%E1%BB%A3ng,t%C6%B0%E1%BB%A3ng%20trong%20th%E1%BA%BF%20gi%E1%BB%9Bi % Anon., n.d FULL STACK DEVELOPER Online Available at: https:devfull.me HOÀNG, P H., 2015 Online Available at: https:toidicodedao.com20150324solidlagiapdungcacnguyenlysoliddetrothanhlaptrinhviencodecung?fbclid=IwAR2hOXf9Dg_V_H8TfeyD3A5md2fri6nQZVMqTA3QEM6zJBKsdHflZnylBo Javatpoint, n.d Design Pattern Online Available at: https:www.javatpoint.comdesignpatternsinjava Mui, Nguyen Van, 2018 Online Available at: https:viblo.asiapsolidtrongandroidORNZqPmnK0n Nitendratech, 2018 ObjectOriented Programming concepts Online Available at: https:www.nitendratech.comprogrammingobjectorientedprogramming Oloruntoba, S., 2020 Online Available at: https:www.digitalocean.comcommunityconceptual_articlessolidthefirstfiveprinciplesofobjectorienteddesignliskovsubstitutionprinciple Oracle, 2012 Object Class Definitions Online Available at: https:docs.oracle.comjavasejnditutorialldapschemaobject.html Shvets, A., 2021 Dive Into DESIGN PATTERNS s.l.:s.n sourcemaking, n.d behavioral patterns Online Available at: https:sourcemaking.comdesign_patternsbehavioral_patterns sourcemaking, n.d structural patterns Online Available at: https:sourcemaking.comdesign_patternsstructural_patterns Techopedia, 2011 Design Pattern Online Available at: https:www.techopedia.comdefinition18822designpattern TopDev, 2019 SOLID gì? Áp dụng SOLID để trở thành lập trình viên giỏi Online Available at: https:topdev.vnblogsolidlagi Tutorial, O., n.d Object Class Definitions Online Available at: https:docs.oracle.comjavasejnditutorialldapschemaobject.html W3schools, n.d C++ OOP Online Available at: https:www.w3schools.comcppcpp_oop.asp ... https:topdev.vnblogsolidlagi?fbclid=IwAR2UzzITTxPd3eXG7b4kpG40kJYj3pMs_kSnYo30wjPlMlo61F8A4pveS80:~:text=L%E 1% BA%ADp%20tr%C3%ACnh%20h%C6%B0%E1%BB%9Bng%20%C4% 91% E1%BB%91i%20t%C6 %B0%E1%BB%A3ng,t%C6%B0%E1%BB%A3ng%20trong%20th%E1%BA%BF%20gi%E1%BB%9Bi % Anon.,... Abstraction 10 Encapsulation 10 Polymorphism 11 c) SOLID 11 S Singleresponsibility Principle 11 O Openclosed Principle... Example 10 Figure 5: Encapsulation Example 11 Figure 6: Polymorphism Example 11 Figure 7: Usecase for Scenario 14 Figure 8: Class

ASSIGNMENT FRONT SHEET Qualification TEC Level HND Diploma in Computing Unit number and title Unit 20: Advanced Programming Submission date 30/06/2022 Date Received 1st submission Re-submission Date Date Received 2nd submission Student Name Nguyen Huy Hoang Student ID GCH200739 Class GCH0908 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 P3 P4 M3 M4 D3 D4  Summative Feedback: Grade:  Resubmission Feedback: Assessor Signature: Internal Verifier’s Comments: Signature & Date: Date: Table of Contents A INTRODUCTION B SCENARIO ANALYSIS SCENARIO DIAGRAM C 2.1 Use-case Diagram 2.2 Class Diagram 10 IMPLEMENTATION 16 Code(Related to Class Diagram) 16 1.1 Loan Concrete Class 16 1.2 Client Concrete Classes 22 1.3 Credit Checker Classes 24 1.4 Loans Factory Method Design Pattern Classes 27 Code(Some Represented Codes in GUI) 31 Program ScreenShots 35 D DISCUSSION 40 Range of Similar Patterns 40 1.1 Briefly Summary of Some Similar Design Patterns to Factory Method 40 1.2 Explain Why Factory Design Pattern is The Most Suitable for this Scenario 41 Usage of Patterns 43 References 44 List of Table Table 1: Signup usecase Table 2: MakeLoan usecase Table 3: View Profile usecase Table 4: Logout Usecase 10 List of Figures Figure 1: Use-case diagram Figure 2: Class Diagram 10 Figure 3: Loans Concrete Classes 11 Figure 4: Client Concrete Class 12 Figure 5: Loans Factory Method Design Pattern 14 Figure 6: Credit Checker Classes 15 Figure 7:Enum 15 Figure 8: Loans CLass 16 Figure 9: HotLoans Class 17 Figure 10: Unsecured Loan Class 18 Figure 11: Overdraft Loan Class 19 Figure 12: InstalmentLoan Class 20 Figure 13: MortgageLoan class 21 Figure 14: User Class 22 Figure 15:Bank Class 23 Figure 16: Item class 24 Figure 17: ICreditChecker interface 25 Figure 18: FastCreditChecker Class 25 Figure 19: ComplexCreditChecker class 26 Figure 20: ServiceChecker Class 26 Figure 21: AutomaticChecker Class 27 Figure 22: ILoanFactory Interface 28 Figure 23: HotLoanFactory Class 28 Figure 24: UnsecuredLoanFactory Class 29 Figure 25: OverdraftLoanFactory Class 29 Figure 26: InstalmentLoanFactory Class 30 Figure 27: MortgageLoanFactory Class 31 Figure 28: Main Form Typical Snippet code 32 Figure 29: AvailableLoanService Form Snippet Code 33 Figure 30: MortgageLoan Form 34 Figure 31: Home Form of app 35 Figure 32: Home Form when unlocking other functions 36 Figure 33: Loan Services Form 37 Figure 34: Profile form 37 A INTRODUCTION In programming, when faced with some problems which are related to OOP or class family organisation, one of the solutions which would be helpful is the design pattern Design patterns are understood as all-purpose, repeatable solutions to issues that crop up frequently The best practices are those that seasoned developers follow Patterns are not entire pieces of code, but they may be used as a model to solve a particular issue Patterns may be used to compare design problems in any domain since they are reusable To get more understandable, this report will present the development of the "GetH1gh" application, which has the problem related to the initialization of an instance of the class and this will be solved by one of the creational patterns The detailed processing, designing, coding and explaining will be presented below The report also provides screenshots for illustrations and analysis as well as evaluates the most suitable design pattern B SCENARIO ANALYSIS SCENARIO "GetH1gh" is a relatively famous financial aid office recently, their slogan is wishing to change its approach to finance, helping people have a better life by providing quick - easy - transparent service Now, when being legalized after operating the long outlaw period, "GetH1gh" is planning to develop an online finance application that will help its customers to make loans more straightforward or even create a mortgage loan package online The online financial application of "GetH1gh" has not been completed yet and is being tested with one of its main functions, which is to initiate loan packages Specifically, there are five primary loan packages of "GetH1gh" including unsecured loans; overdraft loans; instalment loans; mortgage loans and hot loans Each loan also has its own distinct features:  The unsecured loan package will have the highest interest rate is fixed at 21%/year and does not require any collateral Additionally, the procedures for an unsecured loan are quite simple and the credit  For overdraft, it loan limit will be based on the balance of the customer's bank account and the liability and interest of the overdraft will be calculated based on the outstanding balance and the time of the debit The overdraft package could have collateral or not, if there is any collateral to make an overdraft loan, the interest rate of it will decrease significantly  Installment loans will need to declare the items to be paid in instalments, the interest rate is based on the term that the customer will deal with the office The amount and prepayment also will be calculated automatically based on the instalment item  The mortgage loans may need documents of the collateral as well as the loan purpose In case the mortgage collateral has no proven document, the interest rate will be pretty high The loan limit of a mortgage loan is 170 % of the total value of the collateral  Lastly, the special Loan package of "Geth1gh" is a hot loan, its procedures are very simple However, its interest rate is very high Because of the incompetence of their dev team, our team was invited to assist them in developing this functionality DIAGRAM 2.1 Use-case Diagram Here is the use case of entire the program Figure 1: Use-case diagram Explanation: Use case Name Created by: Date Created Description: Actors: Pre-conditions: Post Conditions: Flow: Alternative Course: Exception: SignUp Mr Hoang Last Updated By: Mr Hoang 30/06/2022 Last Revision Date 30/06/2022 This use case describes the process of Signing up the new user’s data  User  The user had to download and install this application;  The system handles and stores the data of the input from the user 1) User clicks on the “Sign up” button on the home form of the app; 2) User fill in the text boxes with appropriate input and format 3) User Click on the button check and the system performance checks the validation of each text boxes 4) System stores and handle the data from the user 5) Finish  Application is no longer approved for use(occurs at step 1); Requirements:  Crashing; The appropriate of the system and user; Table 1: Signup usecase Use case Name Created by: Date Created Description: Actors: Pre-conditions: Post Conditions: Flow: MakeLoan Mr Hoang Last Updated By: Mr Hoang 30/06/2022 Last Revision Date 30/06/2022 This use case describes the process of making the loan  User  The user had to download and install this application;  The user has already done the “Signup” use case;  The system handles and stores the data of the selections of the user  The system stores the input from the user User clicks on the “MakeLoan” button on the home form of the app System performs credit Check System displays the available Loan for the user based on credit; User performs making Loan User fill in the text boxes in the Loan form System updates the time System and user repeat steps to until the user clicks the “back” button; Alternative Course: Finish; In step of the Flow, the user can make different types of loan packages: 1) Make the hot loan one time; 2) Make the unsecured loan one time; 3) Make the overdraft loan one time; 4) Make the instalment loan one time; 5) Make the mortgage loan one time; Exception: Requirements: Table 2: MakeLoan usecase The use case continues at step of the flow  Application is no longer approved for use(occurs at step 1);  Crashing; The appropriate of the system and user; Use case Name Created by: Date Created Description: Actors: Pre-conditions: Post Conditions: Flow: Alternative Course: View Profile Mr Hoang Last Updated By: Mr Hoang 30/06/2022 Last Revision Date 30/06/2022 This use case describes the activities of viewing the profile  User  The user had to download and install this application;  The user had signed up successfully;  The system handles and stores the data of the selections of the user User clicks on the “Profile” button on the home form of this app; System displays the information of the user; Finish; In step of the Flow, the user can cancel the existed loan in the list: Enter the index of the loan which the user wants to cancel; Pay for money fine; System store change; Exception: Requirements: The use case continues at step of the Normal Course  app is no longer approved for use(occurs at step 1);  Crashing; The appropriate of the system and user; Table 3: View Profile usecase Use case Name Created by: Date Created Description: Actors: Pre-conditions: Post Conditions: Flow: Alternative Course: Exception: Log out Mr Hoang Last Updated By: Mr Hoang 30/06/2022 Last Revision Date 30/06/2022 This use case describes the moment when the user clicks logout this game  User  The user had to download and install this game;  The User had to Sign up in this app;  The system handles the data of the selections of the user User clicks on the “Logout” button on the menu; System handles the selection of the user; System performs signing out the data of this user; Finish;  Lag; Requirements: The appropriate of the system and user; Table 4: Logout Usecase 2.2 Class Diagram a) Diagram: Figure 2: Class Diagram Explanation: OverdraftLoanFactory class is one of the LoanFactory Concrete Classes which implement the IloanFactory Interface and it also implements the CreateLoans method in order to change the resulting Loan type from Loans to OverdraftLoan Exceptionally, the datatype of the CreateLoans method still is the “Loans” type, although the OverdraftLoan is returned from the method This way the OverdraftLoanFactory can stay independent of concrete Loan classes Because Overdraft Loan has two options which are making an Overdraft Loan without Collateral and without Collateral, The Interest and something else also change based on two options So, this Factory class also applies overloading on the CreateLoans method and put them with a different number of parameters The first CreateLoans method returns the null or the empty Loan The third CreateLoans method will take the option in which the user has collateral and it takes five parameters: amount(double), the user(User), loanTerm(double), bank(Bank) and collateral(Item The second CreatLoans method will take less than the third CreateLoans one parameter and it is collateral(Item) because the second CreateLoans will meet the option which doesn’t have collateral It uses the InterestRateImplement instance to calculate the interest rate and calls the LiabilityCalculator instance to calculate the Liability based on the result of the InterestRateImplement service for the UnsecuredLoan after the base UnsecuredLoan object is initialized with the parameters transmitted via the method e) InstalmentLoanFactory Class Figure 26: InstalmentLoanFactory Class Explanation: InstalmentLoanFactory class is one of the LoanFactory Concrete Classes which implement the IloanFactory Interface and it also implements the CreateLoans method in order to change the resulting Loan type from Loans to InstalmentLoan Especially, the datatype of the CreateLoans method still is the “Loans” type, although the InstalmentLoanLoan will be returned from the method This way the InstalmentLoanFactory can stay independent of concrete Loan classes Unlike HotLoans or UnsecuredLoan, the feature of InstalmentLoan is quite complex and the logic implementation of InstalmentLoan Factory also is pretty complex It uses the InterestRateImplement instance to calculate the interest rate and calls the LiabilityCalculator instance to calculate the Liability based on the result of the InterestRateImplement service for the InstalmentLoan after the base InstalmentLoan object is initialized with the parameters transmitted via the method After that, it uses the PrepaymentCalculator to calculate the Prepayment and The Actual Amount of InstalmentLoan f) MortgageLoanFactory Class Figure 27: MortgageLoanFactory Class Explanation: MortgageLoanFactory class is one of the LoanFactory Concrete Classes which implement the IloanFactory Interface and it also implements the CreateLoans method in order to change the resulting Loan type from Loans to the mortgage loan Specifically, the datatype of the CreateLoans method still utilizes the Loans class as type, although the MortgageLoanis returned from the method This way the MortgageLoanFactory can stay independent of concrete Loan classes Because of the not-too-complex feature of the mortgage loan, the logic implementation of MortgageLoanFactory also is quite simple as that It calls the InterestRateImplement instance to calculate the interest rate and calls the LiabilityCalculator instance to calculate the Liability based on the result of the InterestRateImplement service for the MortgageLoanafter the base MortgageLoanobject is initialized with the parameters transmitted via the method Code(Some Represented Codes in GUI) Because the code in GUI is quite long and difficult to present on paper, this section will only cover typical GUI code Typical code snippets that use the class library a) Main Form Typical Snippet Code Figure 28: Main Form Typical Snippet code To help all the forms could synchronize with only one main form(Back or open only with one unique main form), the main form structure has been designed quite like the singleton design pattern The mainForm’s constructor has been private to prevent direct construction calls with the `new` operator from other forms The MainForm class defines the `OpenMainform` method that serves as an alternative to the constructor and lets other forms could access and get or transmit data to the same instance of this main form over and over The mainForm's instance has been initialised in a static field right away in this form The static method OpenMainForm controls the access to the mainForm instance On the first call, it creates a main form object and stores it in the static field On subsequent runs, it returns the existing object of mainForm with the static field b) AvailableLoan Form Typical Snippet Code Figure 29: AvailableLoanService Form Snippet Code This code snippet is the illustration of calling the mainForm only via one unique instance In the OpenServices method, this code calls the main form by initializing the unknown type main variable and assigning it directly with the MainForm by the OpenMainForm method and this method will return the unique main form instance for using this instance in available loan services Form The CreditChecker Classes family also are used mainly in this form Two currently available CreditChecker Types are also initialized and check the credit of the user at the same time The logic of open services for each level of credit also has been shown in the image above, this logic is pretty simple c) MortgageForm(Represent for LoanForm in GUI) Typical Snippet Code Figure 30: MortgageLoan Form The primary responsibility of this form is to show the text boxes for the mortgage loan, get the input from the user and handle it by calling the MortgageFactoryLoan instance The FillInfo method would fill and show the basic info(name, age, identity card number) of the user to the form’s interface Because the Loan limit of a mortgage loan is always calculated based on the value of the collateral; So, there is the calLoanLimit method and it will be called when the collateral data is provided In BtnMakeLoan with the event “click”, the instance of MortgageLoan Factory will be initialized here to create the Loan with the input transmitted from text boxes in the form The Loan will be created via the CreatLoan method of newLoan variable(MortgageLoanFactory instance), this method will return the Completed Mortgage Loan if the parameter is appropriate Thereby, using Factory method help create a Loan with full business logic in creating is get more straightforward than usual Program ScreenShots Here are screenshots of program running step by step: Figure 31: Home Form of app When open Geth1gh app, this form will appear first of all If there are no data of user, except Signup button(the first button), other functions would be locked until program complete checking that data of user is existed This home form will switch to this form if the user clicks on the SignUp button If users want to use this app, they need to fill in the info in this form This form has been developed with full validated textboxes Particularly, each text box also has been validated in appropriate ways In case users fill in the wrong format, the message box will appear to notify users The successful message box will appear if all the textboxes are filled appropriately Figure 32: Home Form when unlocking other functions If the program detect the data of user, the sign up button will be locked immediately and these other functions will be unlocked and could be used right away Figure 34: Profile form The data of user will be display in Profile form(the second button in home form) Figure 33: Loan Services Form When users click on Sercives Button(the third button), the home form will switch to Services form The loan services will be unlocked based on the Credit of users In this image, credit of user is “Sir” (the highest Credit); so, all of Loan service obviously are unlocked Users could click on any Loan service and make loan This form will be switched to when the user clicks on Instalment Loan(Clicking on other services will also appear, and the form is compatible with the loan package) The Form has some textboxes which also are the input to make the Loan based on the features of the chosen Loan These Textboxes also have been validated The Message box will notify users if they enter the wrong input This proves that the validate system of program operating properly and accurately When users complete making an Instalment Loan appropriately, the successful message will appear to notify them that this Loan has been made successfully The information on this Loan will be shown in profile form The “make loan” button would be locked as in the image below Now, the instalment loan’s information is shown in the profile form with a detailed description of any data on this loan And Users also could cancel this loan; however, if users want to cancel this loan, they will get the punishment based on the rules of Geth1gh The Message box will appear and notify that users will be punished if they cancel the Loan The Loan will disappear in the Loanlist if users accept cancelling this Loan and the balance of the user also gets decreased by the punishment of the system If the user doesn’t want to use this app or doesn’t want to use this data of the user, just click on the LogOut button(the last button on the interface) The Data of user will be sign out from system, the SignUp button will be unlocked and other functional button will be locked as the time when the app just be opened D DISCUSSION Range of Similar Patterns 1.1 Briefly Summary of Some Similar Design Patterns to Factory Method Design Pattern Class Diagram Briefly Summary Builder Pattern Using straightforward objects and a disciplined process, the builder pattern constructs complicated objects from simple ones Since it represents one of the greatest ways to construct an item, this kind of design pattern is classified as a creational pattern ImageCre: Builder Design Pattern HowtodoinJava The final object is created step-by-step using a Builder class Separate from other things is this builder (TutorialPoint, n.d.) Advantages:  It makes the distinction between an object's production and representation very evident  Better control over the building process is provided  It enables changing how things are internally represented Abstract Pattern Without mentioning the specifics of their actual subclasses, the Abstract Factory Pattern specifies an interface or abstract class for building families of related (or dependant) objects Therefore, a class may return to a factory of classes thanks to Abstract Factory ImageCre: Abstract Pattern TutorialPoint It is frequently used when a system has to be independent of the creation, composition, and representation of its objects or when a family of related items needs to be utilized together (refactoringGuru, n.d.) Advantages:  The Abstract Factory Pattern separates concrete (implementation) classes from client code  It simplifies the transfer of object families  It encourages uniformity among items Prototype Pattern When creating an object is an enormous undertaking that takes time and effort and resources and we already have an existing object that is equivalent, the prototype design pattern is utilized (RefactoringGuru, n.d.) ImageCre: Buider Pattern Viblo 1.2 A prototype pattern suggests a method for copying the initial object to a new object, which we can subsequently alter to meet our needs The object is copied using cloning in the prototype design pattern Advantages:  It lessens the requirement for subclassing  It conceals the difficulties of making goods  The type of new items that the clients can get is unknown  At runtime, it allows you to add or remove objects Explain Why Factory Design Pattern is The Most Suitable for this Scenario Before it comes to explaining why the factory method pattern is the most suitable, it’s necessary to overview the problem of making the application for this scenario The problem here is that there are different loan types and each loan type also has its own distinct features However, in client code as well as in GUI, when creating an object, the client code wouldn’t know exactly what type(type of Laon Concrete class) of the object needs to be initialized and when initializing any type of Loans, there is still some business logic needs to be handled before this object is created For specific, it's necessary to have some classes which have the method which helps create and decide what type of this object will be and this method also contains business logic to complete the resulting object and also return this object At first glance toward this problem, it can be said that this problem could be solved by applying one of the creational design patterns So, I would go over some creational design patterns which are supposed to be the right fit for this problem and show why the factory method is the most suitable pattern There are design patterns which may be suitable for this scenario: Prototype, Builder, Factory method and abstract factory First of all, the prototype, if it is not in the creational design pattern family, would not be listed here Because it is really not suitable for this scenario, it’s quite like the cloning object machine and each loan actually seems to not have anything in common except its name and type(each loan object also has different parameters such as amount, the customer who make this loan, term, etc…) and the business logic when creating loan may change based on the parameter Secondly, Builder could be applied to make the very complex object step by step, Create the object at the final step, and create the completed object by build function It makes the client code could any logic or algorithm between steps because the function in builder also could return builder until the client code makes calling the build function to create a resulting object Although the builder is more flexible than the Factory method by operating step by step, it also makes this scenario take more time and effort The object of the loan is not too complex and it doesn’t need to have many parts as well as parameters as builder pattern logic so the builder could be viewed as not really seeming to be suitable and the builder actually is suitable for domain object(Complex entity) than for the object of the concrete class Thirdly, The factory method, the most suitable for this scenario, could select and create between the object type, Just call CreateLoan and return the loan immediately The factory method brings about a more straightforward logic and it also enhances the customization such as we can update the object in the future if there are any changing things Especially in this scenario, applying the factory method also helps the loan packages in this app be scalable Lastly, an Abstract factory, this one also is quite suitable for this scenario but it really should be used when this scenario becomes more and more complicated In this case of the current scenario, the problem is not complex enough to apply the abstract factory Specifically, the loan types almost are in a family of the object; So, Without separating the big object cluster from each small object cluster and taking the factory to handle it, I can apply the factory method to handle the business logic in the one method and return the resulting object In the other words, if the scenario extends the project and there are more types of objects not only the Loan package, this time I will need to upgrade the factory method to abstract factory but now the factory method is appropriate enough and it could be said that factory method is most suitable for this application of scenario Usage of Patterns After applying the Factory Design pattern, here is my evaluation of the use of the Factory Design Pattern in this scenario including the advantages and disadvantages of this pattern  Advantages: ☺ Using the factory method allows me to code to an interface and promotes agility when declaring and initializing an object ☺ Applying factory design patterns for making code more flexible(Creating loan objects in client code but not care about loan types) by making it meet the problem of this scenario ☺ Help me avoid using too much branching structure(which may make the code lengthy and confusing when extending the type of Loan object) such as “if-else” or “switch-case” in designing a class to create an object ☺ Separating the business logic and responsibility of making a loan to each different loan type factory Additionally, instead of hard-wiring the entire logic to determine the type and features of the Loan package based on a set of criteria in one Loan concrete class(which violates Single Responsibility one of the SOLID principles and It will make the Loan concrete class has too many functions will become cumbersome and become difficult to read, difficult to read, difficult to maintain) So applying the factory method pattern allows me to delegate these functions to another object and call it in the method of Loan Types factory concrete class, making my code maintainable ☺ The Factory Method Pattern help the Loan concrete classes enforce the encapsulation in my program by just calling a new operator of these classes in the method of factory classes As a consequence, any classes that implement the ILoanFactory interface will be compatible with the code because it only interacts with those classes ☺ The factory method pattern also helps my code could minimize possible code mistakes while ensuring reuse and homogeneity Because applying the factory method design pattern is almost best suitable for my scenario as well as solving the problem in this one, there are a little of unsignificant disadvantages  Disadvantages:  Increasing the scale of applications, may have taken more of my time and effort when designing code and testing as well as implementing my program  The project has quite much class, it might make me confusing after not using it for a long time E CONCLUSION The implementation of the program, the designing of the diagrams as well as UI and the explanation of code, GUI and the reason why the Factory method is the most suitable design pattern for the scenario including the advantages and disadvantages of applying this pattern for my scenario After all, I have got some basically typical knowledge about the benefits as well as applying the design pattern to solve the difficult OOP problems References refactoringGuru, n.d AbstractFactory [Online] Available at: https://refactoring.guru/design-patterns/abstract-factory RefactoringGuru, n.d PrototypeDesignPattern [Online] Available at: https://refactoring.guru/design-patterns/prototype TutorialPoint, n.d Design Patterns - Builder Pattern [Online] Available at: https://www.tutorialspoint.com/design_pattern/builder_pattern.htm

Ngày đăng: 12/06/2023, 09:25

w