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

Assignment 2 Advanced Programming (1651 Distinction)

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 (2.67 MB, 71 trang )

ASSIGNMENT 2 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 Received 2nd submission

Student Name

Bui Quang Minh

Student ID

GCD210325

Class

GCD1104

Assessor name


Nguyen The Nghia

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

Page | 1

P4

M3

M4

D3

D4


 Summative Feedback:

Grade:
Lecturer Signature:

Page | 1

 Resubmission Feedback:


Assessor Signature:

Date:


Table of Contents
INTRODUCTION ................................................................................................................................................................... 4
CHAPTER 1. SCENARIO ANALYSIS .................................................................................................................................... 5
I. Scenario ........................................................................................................................................................................ 5
II. Diagrams ...................................................................................................................................................................... 6
1. Class diagrams ........................................................................................................................................................ 6
2. UseCase diagrams ................................................................................................................................................. 9
CHAPTER 2. IMPLEMENTATION ........................................................................................................................................ 12
I. Code ............................................................................................................................................................................ 12
1. Fund class............................................................................................................................................................... 12
2. StockBroker class .................................................................................................................................................. 13
3. Investor class.......................................................................................................................................................... 15
4. FundService class ................................................................................................................................................. 18
5. StockBrokerService class ..................................................................................................................................... 19
6. InvestorService class ............................................................................................................................................ 21
7. Data class .............................................................................................................................................................. 22
8. CheckValid class .................................................................................................................................................. 22
9. Main method......................................................................................................................................................... 24
10. CreateAccountPage class ............................................................................................................................... 26
11. BrokerPage class................................................................................................................................................. 27
12. InvestorPage class.............................................................................................................................................. 28
II. Program Execution ................................................................................................................................................... 30
1. Broker ...................................................................................................................................................................... 30
2. Investor ................................................................................................................................................................... 33

3. Create Account ................................................................................................................................................... 35
CHAPTER 3. DISCUSSION.................................................................................................................................................. 37
I. Design patterns .......................................................................................................................................................... 37
1. Creational patterns .............................................................................................................................................. 37
1.1 Singleton pattern ............................................................................................................................................ 37
1.2 Factory method pattern ............................................................................................................................... 40
2. Structural patterns ................................................................................................................................................ 43
2.1 Faỗade pattern .............................................................................................................................................. 43

Page | 2


2.2 Composite pattern ......................................................................................................................................... 46
3. Behavioral patterns .............................................................................................................................................. 49
3.1 Command pattern ......................................................................................................................................... 49
3.2 Observer pattern ............................................................................................................................................ 53
II. Similar design patterns ............................................................................................................................................. 56
1. Sington and Factory method patterns............................................................................................................. 56
1.1 Singleton pattern ............................................................................................................................................ 56
1.2 Factory method pattern ............................................................................................................................... 58
2. Observer and Composite patterns ................................................................................................................... 61
2.1 Observer pattern ............................................................................................................................................ 61
2.2 Composite pattern ......................................................................................................................................... 63
3. Detailed explaination .......................................................................................................................................... 63
3.1 Singleton and Factory method patterns.................................................................................................... 63
3.2 Observer and composite patterns .............................................................................................................. 64
III. Usage of my design pattern .................................................................................................................................. 66
1. Observer design pattern ..................................................................................................................................... 66
2. Singleton pattern .................................................................................................................................................. 66
CONCLUSION .................................................................................................................................................................... 67

REFERENCE LIST .................................................................................................................................................................. 70

Page | 3


INTRODUCTION
In the previous assignment, I discussed the OOP, UML, and some crucial design patterns that I have learnt
in class.
In this report, I will start by examining a hypothetical scenario. We'll break it down using diagrams, which
are like visual aids to help me understand better. I will create two types of diagrams: class diagrams and
use case diagrams.
Next, I will dive into the technical side of things. We'll look at the code, which is like the instructions that
make software work. Then, we'll see how these instructions come to life through program execution.
In this last chapter, I will discuss design patterns, which are like problem-solving techniques for software.
Also, explore different design patterns and talk about how they can be used. Finally, I will look at the
advantages and disadvantages of the design pattern I chose.

Page | 4


CHAPTER 1. SCENARIO ANALYSIS
I. Scenario
"Have you ever wondered how to make investing in funds easier, especially for people who don't have
much experience in this complex world? That's the puzzle I'm tackling with the 'MB Capital Fund
Management System.'
Investing can be like putting together a big puzzle. There are lots of pieces to consider, from choosing
the right funds to managing your money and ensuring everything goes smoothly. People often struggle
with these parts, and that's where our system comes in.
Now, let me introduce you to the 'MB Capital Fund Management System.' It's like a helpful tool we're
building to make investing simpler. I'm using special techniques to put all these pieces together in a neat

and organized way. I'll also create easy-to-understand drawings to map out how the software works.
By the end of this project, I'll have real experience in building software that solves these investment
puzzles, making it easier for everyone. It's like learning to build with building blocks while solving real-life
challenges. So, let's dive into the MB Capital Fund Management System!"

Figure 1. Capital Fund illustration

Source: salesforce, 2016

Page | 5


II. Diagrams
1. Class diagrams

Figure 2. Class Diagram (1)

Investor Class:
Attributes:






Name: This represents the name of the investor.
Gmail: The Gmail address is used as a unique identifier for login purposes.
Password: The password is also used for secure login.
Pin: A personal identification number, which is an additional security measure.
Balance: This reflects the amount of money available for placing orders.


Relationships:



An Investor is dependent on a single StockBroker (likely representing a brokerage firm). This
relationship signifies that an investor is under the management of a particular stockbroker.
An Investor can own multiple Funds. The connection between an investor and funds indicates
the funds in which the investor has invested.

Methods:


Page | 6

Deposit: This method allows the investor to add money to their balance. It ensures that the
deposited amount is greater than zero.






Withdraw: Investors can withdraw money from their balance, provided the withdrawal amount is
both positive and within the available balance.
PlaceOrder: Investors can use this method to buy new funds. The method associates the investor
with the purchased fund.
DisplayFunds: This method displays all the funds owned by the investor.
Fund Class:


Attributes:





Name: The name of the fund.
Ticket: A code or identifier for the fund, akin to a unique reference.
InceptionDate: This is the date when the fund was initiated.
ManagementFee: The management fee associated with the fund.



Amount: The amount of money invested in the fund by the investor.

Relationships:


Funds are associated with one or more Investors, signifying that multiple investors can invest in the
same fund.
StockBroker Class:

Attributes:





Name: The name of the stockbroker.
Gmail: The Gmail address for the stockbroker's login.

Password: The password used by the stockbroker for secure login.
isMarketChange: A state variable (likely a boolean) to track changes in the market, used in the
Observer pattern.

Relationships:



StockBroker manages a list of Investors. This relationship represents that the stockbroker is
responsible for overseeing multiple investors.
StockBroker is associated with the Observer pattern, which is typically used for monitoring and
notifying investors about market changes.

Methods:




Page | 7

AddToZone: A method used for adding registered investors to the stockbroker's management
zone. This operation is part of the Observer pattern.
MarketChange: A method used to trigger changes in the market and notify investors about these
changes. This operation is also part of the Observer pattern.
DisplayMyInvestors: This method displays the list of investors that the stockbroker is managing.


Abstract Observer Class:
Methods:




Update: This method is a part of the Observer pattern. It allows observers (in this case, investors)
to be notified of changes.
Investor (Inherited from Observer):

Figure 3. Class Diagram (2)

Each of these services follows the singleton pattern, which ensures that there is only one instance of each
service throughout the application.
FundService:
Attributes:


List of Funds: This collection holds all the funds available in the system.

Methods:





AddFund: Used to add a new fund to the list of funds.
GetFund: Retrieves a specific fund from the list using a unique identifier, such as the fund's ticket.
GetFunds: Returns a list of all available funds.
DisplayFunds: Displays all the funds, which can be helpful for users to view the available
investment options.
InvestorService:

Attributes:



Page | 8

List of Investors: This collection contains information about all the investors registered in the system.


Methods:


CheckAccount: Used for login purposes. It verifies the credentials provided by an investor to
authenticate their account.



AddInvestor: Adds a new investor to the list of registered investors.
StockBrokerService:

Attributes:


List of StockBrokers: This collection maintains information about all the stockbrokers in the system.

Methods:





CheckAccount: Similar to the CheckAccount method in the InvestorService, this is used for

stockbrokers to log in.
GetBrokers: Returns a list of all stockbrokers.
GetBroker: Retrieves specific stockbroker information from the list.
DisplayMyInvestors: Displays the list of investors that a stockbroker is managing.

2. UseCase diagrams
For the StockBroker:
View Funds:
 StockBrokers can view the available funds.
Manage Investors:
 StockBrokers can manage the investors who are under their supervision.
Notify:
 StockBrokers have the ability to notify investors when there is a market change or significant
event. This is a critical use case that involves keeping investors informed and updated about their
investments.

Page | 9


Figure 4. Stockbroker Use Case Diagram

For the Investor:
Create Account:
 Investors can create accounts in the system. This provides their personal and account information
to register as investors.
View Funds:
 Investors can view the list of available funds, allowing them to explore investment options.
Place Order:
 This use case involves investors placing orders to buy new funds. They need to ensure they have
enough balance to make a purchase, and if they don't, they should receive a message

indicating that they need to deposit more funds.
Deposit Money:
 Investors can deposit money into their accounts. This use case should ensure that the amount is
greater than 0, and it increases their account balance.
Withdraw Money:
 Investors can withdraw money from their accounts. The system should validate that they have
enough funds to withdraw and that the amount is not negative.
View My Funds:
 Investors can view the list of funds they have purchased. This allows them to track their
investments.

Page | 10


View Profile:
 Investors can view their profile information, which may include their name, email address, and
account details.

Figure 5. Investor Use Case Diagram

Page | 11


CHAPTER 2. IMPLEMENTATION
I. Code
1. Fund class
public class Fund
{
private string name;
private string ticket;

private DateTime inceptionDate;
private double managementFee;
private decimal amount;
public string Name
{
get { return name; }
set { name = value; }
}
public string Ticket
{
get { return ticket; }
set { ticket = value; }
}
public DateTime InceptionDate
{
get { return inceptionDate; }
set { inceptionDate = value; }
}
public double ManagementFee
{
get { return managementFee; }
set { managementFee = value; }
}
public decimal Amount
{
get { return amount; }
set { amount = value; }
}
public Fund(string name, string ticket, DateTime inceptionDate, double managementFee)
{

Name = name;
Ticket = ticket;
InceptionDate = inceptionDate;
ManagementFee = managementFee;
Amount = 0;
}
public override string ToString()
{
return String.Format("|{0,-38}|{1,-7}|{2,-15}|{3,-15}|", Name, Ticket,
InceptionDate.ToString("d"), ManagementFee + "%");
}
}

Attributes




Name: stores the title of the fund.
Ticket: used to hold a unique code or identifier for the fund.
InceptionDate: represents the date when the fund was initiated or created. It uses the DateTime
data type to store the creation date.

Page | 12





ManagementFee: stores the percentage of management fees associated with the fund. It

represents the ongoing expenses that investors may incur.
Amount: keeps track of the amount of money invested in this fund by investor. It starts at 0 and
increases as investor deposit funds.

Method:


The ToString method overrides the default behaviour. It formats and returns a string representing
the fund's details. The format describes the name, ticket, inception date, and management fee.

2. StockBroker class
public class StockBroker
{
private string name;
private string gmail;
private string password;
private List<Investor> myInvestors = new List<Investor>();
private Boolean isMarketChange;
public string Name
{
get { return name; }
set { name = value; }
}
public string Gmail
{
get { return gmail; }
set { gmail = value; }
}
public string Password
{

get { return password; }
set { password = value; }
}
public Boolean IsMarketChange
{
get { return isMarketChange; }
set { isMarketChange = value; }
}
public StockBroker(string name, string gmail, string password)
{
Name = name;
Gmail = gmail;
Password = password;
isMarketChange = false;
}
public void AddToZone(Investor investor)
{
myInvestors.Add(investor);
}
public void MarketChange(Fund fund, string trend)
{
IsMarketChange = true;
if (trend == "1")
NotifyInvestors(fund.Ticket, "is growing...");
else
NotifyInvestors(fund.Ticket, "is declining...");
}
public void NotifyInvestors(string ticket, string message)
{
foreach (var investor in myInvestors)


Page | 13


{
investor.Update(ticket, message);
}
}
public override string ToString()
{
return $"Broker: {Name}, Gmail: {Gmail}";
}
public string DisplayMyInvestors()
{
string text = "*) My Investors List \n";
text += String.Format("|{0,-10}|{1,-20}|{2,-20}|\n", "Name", "Gmail", "Joined Funds");
int count = 1;
foreach (var investor in myInvestors)
{
if (myInvestors.Count() == count)
{
text += String.Format("|{0,-10}|{1,-20}|", investor.Name, investor.Gmail);
var joinedFunds = string.Join("-", investor.myFunds.Select(fund => fund.Ticket));
text += string.Format("{0,-20}|", joinedFunds);
}
else
{
text += String.Format("|{0,-10}|{1,-20}|", investor.Name, investor.Gmail);
var joinedFunds = string.Join("-", investor.myFunds.Select(fund => fund.Ticket));
text += string.Format("{0,-20}|\n", joinedFunds);

}
count++;
}
return text;
}
}

Attributes:






Name: stores the name of the stockbroker.
Gmail: used for the stockbroker's email address. It serves as a login identifier.
Password: holds the stockbroker's password, which is also used for login.
myInvestors: a list that maintains the investors managed by the stockbroker. It's used to keep track
of the investors associated with this stockbroker.
IsMarketChange: is a Boolean value indicating whether a market change has occurred. This is a
part of the observer pattern for notifying investors.

Method:








The AddToZone method is used to add investors to the list of investors managed by the
stockbroker.
The MarketChange method is used to simulate a market change. When this method is called, it
sets the IsMarketChange attribute to true and then calls the NotifyInvestors method to inform the
investors about the market change.
The NotifyInvestors method sends notifications to all investors in the stockbroker's list, informing
them about the market change. It passes the ticket and a message to the Update method of
each investor (part of the observer pattern).
The ToString method overrides the default behavior. It formats and returns a string representing
the stockbroker's details, including their name and Gmail.

Page | 14




The DisplayMyInvestors method is used to generate a formatted string that displays a list of
investors managed by the stockbroker. It provides information about the investors' names, Gmail
addresses, and the funds they have joined.

3. Investor class
public class Investor : Observer
{
private string name;
private string gmail;
private string password;
private string pin;
private decimal balance;
public StockBroker myStockBroker;
public List<Fund> myFunds;

public string Name
{
get { return name; }
set
{
if (!string.IsNullOrEmpty(value))
name = value;
else
throw new ArgumentException("Name cannot be empty.");
}
}
public string Gmail
{
get { return gmail; }
set
{
if (!string.IsNullOrEmpty(value) && value.Contains("@"))
gmail = value;
else
throw new ArgumentException("Invalid Gmail address.");
}
}
public string Password
{
get { return password; }
set
{
if (!string.IsNullOrEmpty(value) && value.Length >= 6)
password = value;
else

throw new ArgumentException("Password must be at least 6 characters long.");
}
}
public string Pin
{
get { return pin; }
set
{
if (!string.IsNullOrEmpty(value) && value.Length == 5)
pin = value;
else
throw new ArgumentException("PIN must be exactly 5 characters long.");
}
}
public decimal Balance
{
get { return balance; }
set
{
if (value >= 0)
{
balance = value;

Page | 15


}
else
{
throw new ArgumentException("Balance cannot be negative.");

}
}
}
public string Deposit(decimal money)
{
if (money <= 0)
{
return "Deposit must be bigger than zero!";
}
else
{
Balance += money;
return "Deposited $" + money + " Successfully. New balance: $" + Balance;
}
}
public string WithDraw(decimal money)
{
if (money > 0 && money <= Balance)
{
Balance -= money;
return "Withdrawn $" + money + " Successfully. New balance: $" + Balance;
}
else
{
return "Please, you do not have enough money to withdraw!";
}
}
public Investor(string name, string gmail, string password, string pin, decimal balance,
StockBroker stockBroker)
{

Name = name;
Gmail = gmail;
Password = password;
Pin = pin;
Balance = balance;
myStockBroker = stockBroker;
myStockBroker.AddToZone(this);
myFunds = new List<Fund>();
}
public string PlaceOrder(Fund fund, decimal money)
{
if (money > Balance)
{
return "You do not have enough money, deposit more money.";
}
Fund foundFund = myFunds.Find(f => f == fund);
if (foundFund == null)
{
Fund myFund = fund;
myFund.Amount = money;
Balance -= money;
myFunds.Add(myFund);
return "Remember to manage the fund regularly.";
}
else
{
Balance -= money;
foundFund.Amount += money;
return "The money has been accumulated.";
}

}

Page | 16


public string DisplayMyFunds()
{
if (myFunds.Count < 1)
{
return "You haven't own any funds";
}
int count = 1;
string text;
text = "*) My Funds List \n";
text += String.Format("|{0,-38}|{1,-7}|{2,-15}|{3,-15}|\n", "Name", "Ticket", "Management
Fee", "Amount");
foreach (Fund f in myFunds)
{
if (myFunds.Count() == count)
{
text += String.Format("|{0,-38}|{1,-7}|{2,-15}|{3,-15}|", f.Name, f.Ticket,
f.ManagementFee + "%", "$" + f.Amount);
}
else
{
text += String.Format("|{0,-38}|{1,-7}|{2,-15}|{3,-15}|\n", f.Name, f.Ticket,
f.ManagementFee + "%", "$" + f.Amount);
}
count++;
}

return text;
}
public override string ToString()
{
return "=> Detail information\n" +
$"Name: {Name}, \n" +
$"Gmail: {Gmail}, \n" +
$"Pin: {Pin}, \n" +
$"Balance: ${Balance} \n" +
$"=> Broker information \n" +
$"Name: {myStockBroker.Name}, \n" +
$"Gmail: {myStockBroker.Gmail}";
}
public override void Update(string ticket, string message)
{
Console.WriteLine($"{Name} got the news that {ticket} {message}");
}
}

Attributes:








Name: stores the name of the investor.
Gmail: holds the investor's email address, which serves as a login identifier.

Password: used to store the investor's password for login.
Pin: represents the personal identification number (PIN) of the investor.
Balance: keeps track of the investor's current financial balance. This balance is used to place
orders for funds and manage investments.
myStockBroker: refers to the stockbroker associated with the investor. Each investor is managed
by a particular stockbroker.
myFunds: maintains a list of funds owned by the investor.

Method:

Page | 17











The Deposit method is used to add money to the investor's balance. It checks whether the
deposited amount is greater than zero.
The Withdraw method allows the investor to withdraw money from their balance. It verifies that
the withdrawal amount is greater than zero and doesn't exceed the available balance.
The PlaceOrder method is used for buying new funds or accumulating money in an existing fund.
It checks if the investor has enough balance to place an order. If the fund is new, it creates a
new fund instance and deducts the money from the balance, adding the fund to the list. If the
fund already exists in the investor's portfolio, it accumulates the money in that fund.

The DisplayMyFunds method generates a formatted string displaying the list of funds owned by
the investor. It provides details such as the fund's name, ticket, management fee, and the
amount invested in each fund.
The ToString method returns a comprehensive string containing the investor's personal information
and details of the associated stockbroker.
The Update method is part of the observer pattern. It is called when the investor receives
notifications about market changes. This method prints a message to the console, informing the
investor about the change in a specific fund and the associated message.

4. FundService class
public sealed class FundService
{
private static FundService instance;
private List<Fund> funds = null;
private FundService()
{
if (funds == null)
{
funds = new List<Fund>();
}
}
public static FundService GetInstance()
{
if (instance == null)
{
// Avoid multithread
lock (typeof(FundService))
{
instance = new FundService();
}

}
return instance;
}
// Add Fund to Fund List
public void AddFund(Fund fund)
{
funds.Add(fund);
}
public Fund GetFund(string ticket)
{
foreach (Fund fund in funds)
{
if (fund.Ticket.ToLower() == ticket.ToLower())
return fund;
}
return null;
}
public List<Fund> GetFunds()
{

Page | 18


return funds;
}
public void DisplayFunds()
{
Console.WriteLine("*) Funds List");
Console.WriteLine(String.Format("|{0,-38}|{1,-7}|{2,-15}|{3,-15}|", "Name", "Ticket",
"Inception Date", "Management Fee"));

foreach (var fund in funds)
{
Console.WriteLine(fund.ToString());
}
}
}

Private Instance and Constructor:



The class has a private static field called instance, which holds the single instance of the
FundService class.
The constructor of the FundService is private, it can only be instantiated from within the class.

Methods:






The GetInstance method is a public static method that provides access to the single instance of
the FundService. This method checks if the instance field is null. If it's null, it creates a new instance
of the FundService. To ensure thread safety, it uses a lock statement to make sure that only one
thread can create the instance.
The AddFund method allows me to add funds to the service.
The GetFund method allows me to retrieve a specific fund from the list of funds based on the
fund's ticket.
The DisplayFunds method is responsible for displaying the list of funds.


5. StockBrokerService class
public sealed class StockBrokerService
{
private static StockBrokerService instance;
private List<StockBroker> brokers = null;
private StockBrokerService()
{
if (brokers == null)
{
brokers = new List<StockBroker>();
}
}
public static StockBrokerService GetInstance()
{
if (instance == null)
{
// Avoid multithread
lock (typeof(StockBrokerService))
{
instance = new StockBrokerService();
}
}
return instance;
}
public void AddBroker(StockBroker broker)
{
brokers.Add(broker);
}


Page | 19



×