0% found this document useful (0 votes)
35 views24 pages

Nguyen Duc Anh Assignment 2

The document summarizes an implementation of the Observer design pattern to simulate a meeting scheduling system. It includes a class diagram showing Observer and MeetingSystem classes, with MeetingSystem storing observers in a list. Code is provided for MeetingSystem and Observer classes, with MeetingSystem notifying observers via a NotifyObserver method when the meeting is changed or canceled.

Uploaded by

27ducanh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views24 pages

Nguyen Duc Anh Assignment 2

The document summarizes an implementation of the Observer design pattern to simulate a meeting scheduling system. It includes a class diagram showing Observer and MeetingSystem classes, with MeetingSystem storing observers in a list. Code is provided for MeetingSystem and Observer classes, with MeetingSystem notifying observers via a NotifyObserver method when the meeting is changed or canceled.

Uploaded by

27ducanh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

ASSIGNMENT 2 FRONT SHEET

Qualification BTEC Level 5 HND Diploma in Computing

Unit number and title Unit 20: Advanced Programming

Submission date 3/7/2021 Date Received 1st submission

Re-submission Date Date Received 2nd submission

Student Name Nguyen Duc Anh Student ID GCH17051

Class GCH0805 Assessor name Mr. Tung

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 ducanh

Grading grid

P3 P4 M3 M4 D3 D4
 Summative Feedback:  Resubmission Feedback:

Grade: Assessor Signature: Date:


Lecturer Signature:
Table of Contents
I. Introduction .......................................................................................................................................................................................................... 4
II. Scenario............................................................................................................................................................................................................. 4
1. Scenario............................................................................................................................................................................................................. 4
2. Diagram ............................................................................................................................................................................................................ 4
III. Implementation ................................................................................................................................................................................................ 6
1. Code................................................................................................................................................................................................................... 6
2. Program Screenshots ..................................................................................................................................................................................... 16
IV. Discussion........................................................................................................................................................................................................ 20
1. Similar Pattern ............................................................................................................................................................................................... 20
2. Usage of Pattern ............................................................................................................................................................................................. 23
V. Conclusion .......................................................................................................................................................................................................... 24
VI. Reference ........................................................................................................................................................................................................ 24
Observer scenario and code implement

I. Introduction
The article is a continuation of the first assignment article, consisting of three main parts. Part one continues with the Observer
Pattern scenario but provides more details on the Class Diagram. Part two explains and implements the code of the scenario with the
topic of a system for sending notices and updating meeting schedules. The final section provides some more Design Patterns and
details the advantages and disadvantages of the Observer Pattern in the scenario.
II. Scenario
1. Scenario
This article simulates a system that works as follows: A system called Meeting System functions as an application to
book, change, and cancel meeting schedules, and then send notifications simultaneously to other members. members of the
company: employees, secretaries and project managers. These members adjust their duties to accommodate the change. For
example, employees work from home when the meeting format is online.
According to GoF, the system has dependencies between objects so that when a subject object changes state, all related objects
are notified and updated automatically. This pattern is called the Observer Pattern. In the scenario above, there are multiple
observers (Staffs, Secretaries, Project manager) who are observing a particular subject (Meeting System). Subscriber observers
want to be notified when there are changes inside the Meeting System. Therefore, it is possible to apply the Observer Pattern to
the above scenario.
2. Diagram
Diagram 1 : Meeting System Observer Pattern

Observer class has two properties name and id. The name acts as a parameter to pass to the Observer constructor, and the
id is automatically generated and incremented with each observer added to the list. In addition, it also has an Update method to
update changes and an abstract method Todo to simulate what the observer will do after receiving the subject's change
notification. Staff, Secretary and Project Manager classes inherit Observer class and override Todo method.
The Meeting System class includes an Observer list to store observers. The NotifyObserver method is executed after the
ChangeTime or Cancel Meeting method is called. In that Notify method, the Update and ToDo methods are executed for each
element in the Observer list.
In addition, the Meeting System class inherits the Program Menu class to perform some functions such as menu printing
and validation.
III. Implementation
1. Code
Meeting System Class
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4.
5.
6. namespace MeetingSystem
7. {
8. public class MeetingSystem : MenuProgram
9. {
10. private List<Observer> observers;
11. public MeetingSystem()
12. {
13. observers = new List<Observer>();
14.
15. }
16.
17. public string Date { get; set; }
18. public int Hour { get; set; }
19. public int Minute { get; set; }
20. public string Form { get; set; }
21. private void AddObserver()
22. {
23. AddProgram submenu = new AddProgram();
24. submenu.Run();
25. observers = submenu.Observers;
26. }
27. private void RemoveObserver()
28. {
29. Console.Write("Enter ID: ");
30. int id = Convert.ToInt32(Console.ReadLine());
31. bool found = false;
32. foreach (Observer acc in observers.ToList())
33. {
34. if (acc.ID == id)
35. {
36. observers.Remove(acc);
37. found = true;
38. }
39. }
40. if (!found) Console.WriteLine("No account with id = " + id);
41. }
42. private void NotifyObserver()
43. {
44. foreach (Observer observer in observers)
45. {
46. observer.Todo(this);
47. Console.Write("Id:" + observer.ID + " Name: " + observer.Name + " ");
48.
49. observer.Update(this);
50.
51. }
52. Console.WriteLine();
53. }
54. protected override void DoTask(int opt)
55. {
56. switch (opt)
57. {
58. case 1: AddObserver(); break;
59. case 2: RemoveObserver(); break;
60. case 3: ChangeTime(); break;
61. case 4: CancelMeeting(); break;
62. case 5: break;
63. default: Console.WriteLine("Invalid"); break;
64. }
65. }
66. private void CancelMeeting()
67. {
68. if (Date == null)
69. {
70. Console.WriteLine("Meeting schedule not available");
71. }
72. else
73. {
74. Date = null;
75. NotifyObserver();
76. }
77. }
78. private void ChangeTime()
79. {
80. if (observers.Count == 0)
81. {
82. Console.WriteLine("No observers, pls add some");
83. }
84. else
85. {
86. if (Date == null)
87. {
88. Console.WriteLine("No meeting schedule");
89. }
90. else
91. {
92. Console.WriteLine("Current meeting schedule: {0} : {1} date {2} ({3})",
Hour, Minute, Date, Form);
93.
94. }
95. string date;
96. do
97. {
98. Console.WriteLine("Update Date (DD/MM/YYYY): ");
99. date = Console.ReadLine();
100. } while ((IsDate(date) == false));
101. Date = date;
102.
103. Console.WriteLine("Update Hour: ");
104. Hour = Convert.ToInt32(Console.ReadLine());
105. Console.WriteLine("Update minute: ");
106. Minute = Convert.ToInt32(Console.ReadLine());
107. Console.WriteLine("Update meeting form(1:Online / 2:Offline");
108. int id = Convert.ToInt32(Console.ReadLine());
109. switch (id)
110. {
111. case 1: Form = "Online"; break;
112. default: Form = "Offline"; break;
113.
114. }
115.
116.
117. NotifyObserver();
118. }
119. }
120. protected override void PrintMenu()
121. {
122. Console.WriteLine("-------Meeting-------");
123. Console.WriteLine("1. Add Observer");
124. Console.WriteLine("2. Remove Observer");
125. Console.WriteLine("3. Change Meeting Time");
126. Console.WriteLine("4. Cancle Meeting");
127. Console.WriteLine("0. Exit");
128. }
129.
130. }
131. }

Declare the class List<Observer> which represents a list of objects that can be accessed by index (line 10). It belongs to
the System.Collection.Generic namespace. Initializes a new instance of the List<T> class in the construtor (line 11).
Declare variables as private (date, hour, minute, form) and provide public get and set properties to access and update their
values. { get; set } is an abbreviated form (line 17 -20).
Instantiate an object named submenu in the AddObserver function to add new observers to the Observer list in the
AddProgram class(line 23). Then attach the elements of the Observer list in the AddProgram class to the Observer list of the
MeetingSystem class (line 25).
The Remove Observer method helps observers unsubscribe by using a for-each loop to find the elements in the
Observer list that have the same id as the observer to be removed. This value is entered by the user (line 27 – 41).
Similar to Remove Observer, the NotifyObserver method uses a for-each loop to iterate over all the elements in the Observer
list and executes Update and Todo when it is called (line 42 – 53). The keyword “this” to pass an object as a parameter to the
method in the class itself (MeetingSystem).
The Meeting System class overrides the Print Menu and Do Task methods of the Menu Program class. Many If-else
statements are used to build the logic of the system. For example, to check if a meeting schedule exists (line 68 -76) or to
check if the system has any observers using the count method in List (line 80 - 83).
The NotifyObserver method is executed after the ChangTime or Cancle Meeting method is called (line 57 and line
117).

Observer Class
132. using System;
133.
134.
135. namespace MeetingSystem
136. {
137. public abstract class Observer
138. {
139.
140. protected string name;
141. public string Name
142. {
143. get { return name; }
144. set { name = value; }
145. }
146.
147. private static int num = 100;
148. protected int id;
149. public int ID
150. {
151. get { return id; }
152. }
153.
154. public Observer(string name)
155. {
156. this.name = name;
157. id = num++;
158. }
159. public virtual void Update(MeetingSystem subjects)
160. {
161.
162. if (subjects.Date != null)
163. Console.WriteLine("Update meeting: {0}:{1} date: {2}. Meeting form: {3}",
subjects.Hour, subjects.Minute, subjects.Date, subjects.Form);
164. else
165. Console.WriteLine("The meeting schedule has been cancelled. All employees
continue to work as planned");
166. }
167. public abstract void Todo(MeetingSystem subjects);
168.
169. }
170. }

The Observer class is an abstract class that includes an Observer constructor with a string name as a parameter. The id
will be automatically incremented by one each time this constructor is called (line 154 -157).
The Update method is responsible for displaying the status change of the Meeting System (information, time and form of the
meeting). So, to be able to access these properties, it is necessary to pass object (MeetingSystem) to Update method as paramator
named subjects (line 159). This method can be overridden by an Observer, so the virtual keyword is used.
Observer Derived Class
171. using System;
172.
173.
174. namespace MeetingSystem
175. {
176. public class Staff : Observer
177. {
178.
179. public Staff(string name) : base(name)
180. {
181.
182. }
183.
184. public override void Todo(MeetingSystem subjects)
185. {
186.
187. Console.WriteLine("STAFF");
188. if(subjects.Form == "Online" && subjects.Date != null)
189. {
190. Console.WriteLine("Staff works at home");
191. }
192. else if (subjects.Form == "Offline" && subjects.Date != null)
193. {
194. Console.WriteLine("Staff works at company");
195. }
196.
197. }
198. }
199. }

200. using System;


201.
202.
203. namespace MeetingSystem
204. {
205. public class Secretary : Observer
206. {
207.
208. public Secretary(string name) : base(name) { }
209.
210. public override void Todo(MeetingSystem subjects)
211. {
212. Console.WriteLine("SECRETARY");
213. if (subjects.Form == "Online" && subjects.Date != null)
214. {
215. Console.WriteLine("Work online at home");
216. Console.WriteLine("Record the meeting");
217. }
218. else if (subjects.Form == "Offline" && subjects.Date !=null)
219. {
220. Console.WriteLine("Work at the office");
221.
222. }
223.
224. }
225. }
226. }

227. using System;


228.
229. namespace MeetingSystem
230. {
231. public class ProjectManager : Observer
232. {
233.
234.
235. public ProjectManager(string name) : base(name)
236. {
237.
238.
239. }
240.
241. public override void Todo(MeetingSystem subjects)
242. {
243. Console.WriteLine("PROJECT MANAGER");
244.
245. if (subjects.Form == "Online" && subjects.Date != null)
246. {
247. Console.WriteLine("Has to come to the office");
248. Console.WriteLine("Create meeting room online");
249. }else if (subjects.Date != null)
250. Console.WriteLine("Work at office");
251.
252. }
253. }
254. }

Three classes Staff, Secretary and Project Manager inherit Observer class and override ToDo method according to the
task of each class in the company

Menu Program Class


255. using System;
256. using System.Text.RegularExpressions;
257.
258. namespace MeetingSystem
259. {
260. public abstract class MenuProgram
261. {
262.
263. public void Run()
264. {
265. bool running = true;
266. while (running)
267. {
268. PrintMenu();
269. int opt = GetOption();
270. DoTask(opt);
271. if (opt == 0) running = false;
272. }
273. }
274. private int GetOption()
275. {
276. Console.WriteLine("Enter your choice");
277. int option = Convert.ToInt32(Console.ReadLine());
278. return option;
279. }
280. protected abstract void DoTask(int opt);
281. protected abstract void PrintMenu();
282.
283. public static bool IsDate(string date)
284. {
285. string strRegex = @"\b(((0?[469]|11)/(0?[1-9]|[12]\d|30)|(0?[13578]|1[02])/(0?[1-
9]|[12]\d|3[01])|0?2/(0?[1-9]|1\d|2[0-8]))/([1-9]\d{3}|\d{2})|0?2/29/([1-
9]\d)?([02468][048]|[13579][26]))\b";
286.
287.
288. Regex re = new Regex(strRegex);
289.
290.
291. if (re.IsMatch(date))
292. return (true);
293. else
294. return (false);
295. }
296. }
297. }

In addition to the main functions such as printing menus, the Menu Program class also has an isDate method that uses
Regular Expression to validate the date value entered by the user.

Add Program Class


298. using System;
299. using System.Collections.Generic;
300.
301. namespace MeetingSystem
302. {
303. public class AddProgram : MenuProgram
304. {
305. private List<Observer> observers;
306. public List<Observer> Observers
307. {
308. get { return observers; }
309. }
310. public AddProgram()
311. {
312. observers = new List<Observer>();
313. }
314.
315. protected override void DoTask(int opt)
316. {
317. switch(opt)
318. {
319. case 1: AddStaff(); break;
320. case 2: AddSecretary(); break;
321. case 3: AddProjectManager(); break;
322. case 0: break;
323. default: Console.WriteLine("Invalid"); break;
324. }
325. }
326.
327. private void AddProjectManager()
328. {
329. Console.WriteLine("Enter your name: ");
330. string name = Console.ReadLine();
331. ProjectManager pro = new ProjectManager(name);
332. observers.Add(pro);
333. }
334.
335. private void AddStaff()
336. {
337. Console.WriteLine("Enter your name: ");
338. string name = Console.ReadLine();
339. Staff staff = new Staff(name);
340. observers.Add(staff);
341. }
342.
343. private void AddSecretary()
344. {
345. Console.WriteLine("Enter your name: ");
346. string name = Console.ReadLine();
347. Secretary sec = new Secretary(name);
348. observers.Add(sec);
349. }
350.
351. protected override void PrintMenu()
352. {
353. Console.WriteLine("-------Add Observers-------");
354. Console.WriteLine("1. Add Staff");
355. Console.WriteLine("2. Add Secretary");
356. Console.WriteLine("3. Add Project Manager");
357. Console.WriteLine("0. Back");
358. }
359. }
360. }
Similar to the Meeting System class, the Add Program class declares an Observer list and then uses the Get keyword so
that the Meeting System can access this value (line 25). When the AddStaff method is called, the system initializes a staff object
of the Staff class with the parameter name string entered by the user (line 339), and then adds this object to the Observer list
(line 340). The same goes for the AddSecretary and AddProjectManager methods when new observers are registered to the
system.

Program Main
361. using System;
362.
363.
364. namespace MeetingSystem
365. {
366. class Program
367. {
368. static void Main(string[] args)
369. {
370. MeetingSystem meeting = new MeetingSystem();
371.
372. meeting.Run();
373.
374. Console.ReadLine();
375.
376. }
377. }
378. }

2. Program Screenshots
Image 1: Meeting System program
Image 2: Add observer option
Image 3: Add Staff

Image 4 : Change meeting time


Image 5: Observers update state and change

Image 6: Cancel meeting

IV. Discussion
1. Similar Pattern
According to the GoF classification, the Observer Pattern is one of the popular patterns of the Behavioral Pattern. Some
similar other patterns are mentioned below:
Chain of Responsibility
Chain of Responsibility Pattern allows an object to send a request to other objects, but without specifying which object
will receive and process that request. Specifically, the objects that receive the request will be connected to each other in a chain
and send requests along that chain until the request is handled by an object (Gamma, Helm, Johnson and Vlissides, 1994).
Diagram 2: Chain of Responsibility

Handler is an abstract class for handling requests. The abstract method HandleRequest() will be overridden by the
ConcreterHander classes. ConcreteHandler are request handling classes and it can access its successor. If the request is not
handled by an object, the ConcreateHandler sends the request to its successor.
The implement the CoR Pattern works as follows: A client sends a request to a chain of Handlers. Each Handler in chain in the
chain tries to process the request received from the client. If the first handler (ConcreteHandler1) can handle it, the process stops
and the request is processed. Otherwise, the request will send to the next handler in the chain (ConcreteHandler2).
Mediator
The mediator is another pattern related to how objects connect, communicate with each other. The Mediator Pattern is
defined as encapsulating the interactions of a set of objects in a particular object. And the interaction of this can be changed
independently. This approach promotes loose coupling because objects do not explicitly refer to each other when performing
communication (GP, 2021).
Diagram 3: Mediator Pattern

ConcreteColleague class interacts through the Mediator when it needs to communicate with other Colleagues. Mediator
is an abstract class that defines methods to communicate with Colleague objects. ConcreteMediator implements Mediator
methods and recognizes and manages Colleague objects.
This approach reduces the complexity of "steps of communication" between classes and objects by providing an intermediate
class that handles communication between objects. In addition, Mediator Pattern changes the relationship between objects, which
can be one-to-many (one-to-many) to one-one depending on the expected situation (GP, 2021). Let consider an example:

Image 7: Before using Mediator (GP, 2021)


The figure above depicts a website with four pages. The client can browse from page to page following the line drawn in
the figure. However, a page has too many routes to go to another page, so there will be a lot of duplicate code on many different
pages.

Image 8: After using Mediator (GP, 2021)

The Mediator Pattern is used to encapsulate all these links into a single module and place it in a Mediator object. As the
result, when there are any changes to the Mediator, the Mediator knows how to navigate the page for the client on its own.
Why use Observer Pattern?
As described above, the Meeting System is a system that changes the meeting schedule and sends notifications to all its
accounts. On the other hand, the Observer design pattern is mainly implemented in systems based on state functionality, and the
state is frequently changed. In addition, the system is observed by other components and objects. Other Design Patterns like
Chain of Responsibility or Mediator mentioned above are also related to communication and relationships between many objects.
However, the Chain of Responsibility looks for an object to resolve the request, so the information transmitted is stopped when
the request is resolved. With Observer, information is transferred to all objects. The mediator is concerned with encapsulating
communication methods, it is not applicable in the scenario at all, however, Colleagues can communicate with the mediator
using the Observer pattern. In short, the Meeting System in the scenario resembles the Publisher and subscriber of the Observer
Pattern relationship. That is the reason why using Observer is the most suitable for this situation.
2. Usage of Pattern
Design Patterns are designed to solve specific and repetitive programming cases. Therefore, they have certain strengths
and weaknesses. The following is an analysis of the advantages and disadvantages of using the Observer Pattern in the scenario
of section 1. The advantages:
The first is that the program designs a loose link between the interacting objects. This facilitates the system to add and
remove observers at any time (Staffs, Secretaries, ...) without modifying the object to add new observers.
The Second, the system allows users to send data to many other objects efficiently with just one method (notifyObserver).
Meeting schedules of employees in the company are updated automatically. In addition, Subject and Observer classes are not
changed when this notification is performed.
Basically, the Observer Pattern has solved the core problem of the scenario that is the relationship and automatically
updates when the state changes. However, the system created some unexpected disadvantage:
Firstly, the system only knows a list of observers that includes many company personnel. Therefore, the system does not
allow information to be sent in a priority manner: the manager receives the change notification before other employees. In this
Meeting System, observers are only notified in an order, which is the order of registration.
Secondly, the system sends a change notification to all observed objects. As a result, some employees (observers)
participating in the system but not participating in the meeting also receive the information. To avoid this, they only have to
unregister the system.
V. Conclusion
In summary, the two articles covered a part of knowledge about object-oriented programming and Design Patterns. With the
main topic of Observer Pattern, the article has provided definitions, concepts, how Design Patterns work, how to draw UML diagrams
and execute code with the main topic being Observer. However, the knowledge and information of this article is very basic and
needs to be improved and studied more in the next articles.
VI. Reference

Gamma, E., Helm, R., Johnson, R. and Vlissides, J., 1994. Design patterns.

GP, C., 2021. Java Design Pattern – Mediator - GP Coder). [online] GP Coder. Available at: <https://gpcoder.com/4740-huong-dan-java-design-pattern-
mediator/> [Accessed 2 July 2021].

You might also like