Design Pattern Examples
Overview of object-oriented design patterns
Mediator_User_Classes.cs
Go to the documentation of this file.
1
6
7// The Mediator pattern acts as a go-between for multiple entities that want
8// no knowledge of any of the other entities except at the most abstract
9// level.
10//
11// The classes defined in this module are for handling users. These classes
12// have no knowledge of groups or the mediator class itself.
13//
14// This is a dead simple implementation of the concept of a user. There is
15// only a name being tracked here.
16
17using System;
18using System.Collections.Generic;
19
21{
25 public class User
26 {
31 public User(string name)
32 {
33 Name = name;
34 }
35
36
40 public string Name { get; }
41
47 public override bool Equals(object? obj)
48 {
49 if (obj != null)
50 {
51 if (obj is User)
52 {
53 return ((User)obj).Name == Name;
54 }
55 if (obj is string)
56 {
57 return (string)obj == Name;
58 }
59 }
60 return false;
61 }
62
63
71 public override int GetHashCode()
72 {
73 return Name.GetHashCode();
74 }
75 }
76
77
78 //########################################################################
79 //########################################################################
80
81
87 public class UserList
88 {
92 List<User> _users = new List<User>();
93
98 public string[] UserNames
99 {
100 get
101 {
102 List<string> userNames = new List<string>();
103 foreach (User user in _users)
104 {
105 userNames.Add(user.Name);
106 }
107 userNames.Sort();
108 return userNames.ToArray();
109 }
110 }
111
112
118 public User? FindUser(string name)
119 {
120 return _users.Find(x => x.Equals(new User(name)));
121 }
122
123
130 public void AddUser(string name)
131 {
132 if (String.IsNullOrEmpty(name))
133 {
134 throw new ArgumentNullException("name", "Must specify a user name to add it to the user list.");
135 }
136
137 User newUser = new User(name);
138 if (!_users.Contains(newUser))
139 {
140 _users.Add(newUser);
141 }
142 }
143
144
150 public void RemoveUser(string name)
151 {
152 User existingUser = new User(name);
153 if (_users.Contains(existingUser))
154 {
155 _users.Remove(existingUser);
156 }
157 }
158 }
159}
Represents a user with a name.
override int GetHashCode()
Generate a hash code for this instance.
string Name
The name of the user (read-only).
override bool Equals(object? obj)
Override to compare a User or string to this User.
User? FindUser(string name)
Retrieve the User instance for the specified user name.
void AddUser(string name)
Add the specified user name as a user. Operation ignored if user is already in the list.
void RemoveUser(string name)
Remove the specified user name as a user. Operation ignored if user is not in the list.
List< User > _users
The list of users.
string[] UserNames
The user names contained in this list (read-only). The list is always sorted.
The namespace containing all Design Pattern Examples implemented in C#.