-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_usage.cpp
More file actions
378 lines (307 loc) · 13.2 KB
/
example_usage.cpp
File metadata and controls
378 lines (307 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
/**
* @file example_usage.cpp
* @brief Comprehensive example demonstrating Railway Scheduling System library usage
*
* This file provides practical examples of how to use the Advanced Railway Scheduling
* System library in your own projects. It covers all major components and design patterns.
*/
#include "Railwaysystem.h"
#include <iostream>
#include <vector>
#include <memory>
// Helper function to create time
std::time_t createTime(int hours, int minutes) {
std::tm timeinfo = {};
timeinfo.tm_hour = hours;
timeinfo.tm_min = minutes;
timeinfo.tm_sec = 0;
timeinfo.tm_mday = 1;
timeinfo.tm_mon = 0;
timeinfo.tm_year = 120;
return std::mktime(&timeinfo);
}
/**
* @brief Example 1: Basic Station and Platform Management
*/
void example1_BasicStationManagement() {
std::cout << "\n=== Example 1: Basic Station Management ===\n";
try {
// Create stations with different ID types
std::vector<Station> stations;
stations.emplace_back("DELHI"); // String ID
stations.emplace_back("MUMBAI"); // String ID
// Add lines to Delhi station
auto& delhi = stations[0];
delhi.addLine("Western Line", 1, 1);
delhi.addLine("Central Line", 2, 2);
std::cout << "✅ Successfully created stations and added lines\n";
std::cout << "Delhi Station ID: " << delhi.getStationID() << "\n";
std::cout << "Number of lines: " << delhi.getLines().size() << "\n";
// Try to schedule a train
std::time_t departureTime = createTime(14, 30);
Platform& platform1 = delhi.getLines()[0].getPlatform();
platform1.addStoppage(departureTime);
std::cout << "✅ Train scheduled successfully at 14:30\n";
} catch (const std::exception& e) {
std::cerr << "❌ Error: " << e.what() << std::endl;
}
}
/**
* @brief Example 2: Train Polymorphism and Different Train Types
*/
void example2_TrainPolymorphism() {
std::cout << "\n=== Example 2: Train Polymorphism ===\n";
// Create different types of trains
std::vector<std::shared_ptr<Train>> trains;
trains.push_back(std::make_shared<ExpressTrain>("EXP001", "Rajdhani Express"));
trains.push_back(std::make_shared<LocalTrain>("LOC001", "Mumbai Local"));
trains.push_back(std::make_shared<HighSpeedTrain>("HST001", "Vande Bharat"));
trains.push_back(std::make_shared<FreightTrain>("FRT001", "Cargo Express", 750.0));
// Demonstrate polymorphic behavior
for (const auto& train : trains) {
std::cout << "\n--- " << train->getTrainName() << " ---\n";
train->displayTrainInfo();
std::cout << "100km fare: ₹" << train->calculateTicketPrice(100.0) << "\n";
std::cout << "Stopping time: " << train->getStoppingTime() << " minutes\n";
}
}
/**
* @brief Example 3: Notification System (Observer Pattern)
*/
void example3_NotificationSystem() {
std::cout << "\n=== Example 3: Notification System ===\n";
// Create notification center
auto notificationCenter = std::make_shared<NotificationCenter>();
// Add different types of observers
notificationCenter->addObserver(
std::make_shared<PassengerNotification>("P001")
);
notificationCenter->addObserver(
std::make_shared<StationMasterNotification>("DELHI")
);
notificationCenter->addObserver(
std::make_shared<MaintenanceNotification>()
);
std::cout << "Sending various notifications...\n";
// Send different types of notifications
notificationCenter->notifyDelayUpdate("EXP001", 15);
notificationCenter->notifyPlatformChange("LOC001", 2, 3);
notificationCenter->notifyCancellation("FRT001", "Engine maintenance required");
notificationCenter->notifyMaintenanceAlert("Platform 1", "Signal system needs attention");
}
/**
* @brief Example 4: Scheduling Strategies (Strategy Pattern)
*/
void example4_SchedulingStrategies() {
std::cout << "\n=== Example 4: Scheduling Strategies ===\n";
// Create platform and trains
Platform platform(1);
std::vector<std::shared_ptr<Train>> trains;
trains.push_back(std::make_shared<ExpressTrain>("EXP001", "Express Train"));
trains.push_back(std::make_shared<LocalTrain>("LOC001", "Local Train"));
trains.push_back(std::make_shared<HighSpeedTrain>("HST001", "High Speed Train"));
// Test different scheduling strategies
std::vector<std::unique_ptr<SchedulingStrategy>> strategies;
strategies.push_back(std::unique_ptr<SchedulingStrategy>(new FCFSScheduling()));
strategies.push_back(std::unique_ptr<SchedulingStrategy>(new PriorityScheduling()));
strategies.push_back(std::unique_ptr<SchedulingStrategy>(new OptimalScheduling()));
for (auto& strategy : strategies) {
std::cout << "\nTesting Strategy: " << strategy->getStrategyName() << "\n";
SchedulingContext context(std::move(strategy));
bool success = context.executeScheduling(platform, trains);
std::cout << "Result: " << (success ? "✅ Success" : "❌ Failed") << "\n";
}
}
/**
* @brief Example 5: Passenger Management and Dynamic Pricing
*/
void example5_PassengerManagement() {
std::cout << "\n=== Example 5: Passenger Management ===\n";
PassengerManagementSystem pms;
// Register passengers
std::cout << "Registering passengers...\n";
bool success1 = pms.registerPassenger("P001", "John Doe", "9876543210", "john@email.com");
bool success2 = pms.registerPassenger("P002", "Jane Smith", "9876543211", "jane@email.com");
std::cout << "P001 registration: " << (success1 ? "✅ Success" : "❌ Failed") << "\n";
std::cout << "P002 registration: " << (success2 ? "✅ Success" : "❌ Failed") << "\n";
// Book ticket with regular pricing
std::cout << "\n--- Booking with Regular Pricing ---\n";
std::time_t journeyDate = createTime(14, 30);
std::string ticketID1 = pms.bookTicket(
"P001", "EXP001", "DELHI", "MUMBAI",
journeyDate, Ticket::TicketClass::AC_2_TIER, 1000.0
);
if (!ticketID1.empty()) {
std::cout << "✅ Ticket booked: " << ticketID1 << "\n";
pms.confirmTicket(ticketID1);
}
// Switch to dynamic pricing
std::cout << "\n--- Switching to Dynamic Pricing ---\n";
pms.setPricingStrategy(
std::unique_ptr<PricingStrategy>(new DynamicPricing())
);
std::string ticketID2 = pms.bookTicket(
"P002", "HST001", "DELHI", "BANGALORE",
journeyDate, Ticket::TicketClass::AC_1_TIER, 2000.0
);
if (!ticketID2.empty()) {
std::cout << "✅ Ticket booked with dynamic pricing: " << ticketID2 << "\n";
}
// Display booking summary
std::cout << "\n--- Booking Summary ---\n";
auto ticket1 = pms.findTicket(ticketID1);
auto ticket2 = pms.findTicket(ticketID2);
if (ticket1) ticket1->displayTicket();
if (ticket2) ticket2->displayTicket();
std::cout << "Total System Revenue: ₹" << pms.getTotalRevenue() << "\n";
}
/**
* @brief Example 6: Performance Analytics (Singleton Pattern)
*/
void example6_PerformanceAnalytics() {
std::cout << "\n=== Example 6: Performance Analytics ===\n";
// Get singleton instance
auto analytics = PerformanceAnalytics::getInstance();
// Record sample performance data
std::cout << "Recording performance data...\n";
analytics->recordDelay("EXP001", 10);
analytics->recordDelay("EXP001", 15);
analytics->recordDelay("LOC001", 5);
analytics->recordDelay("HST001", 3);
analytics->recordStationTraffic("DELHI");
analytics->recordStationTraffic("DELHI");
analytics->recordStationTraffic("MUMBAI");
analytics->recordRevenue("DELHI-MUMBAI", 25000.0);
analytics->recordRevenue("DELHI-BANGALORE", 35000.0);
analytics->recordPlatformUtilization("P1", 85.5);
analytics->recordPlatformUtilization("P2", 72.3);
analytics->recordCancellation("FRT001");
std::cout << "✅ Data recorded successfully\n";
// Generate comprehensive report
analytics->generatePerformanceReport();
// Get specific metrics
std::cout << "\n--- Quick Metrics ---\n";
std::cout << "System Average Delay: " << analytics->getSystemWideAverageDelay() << " minutes\n";
std::cout << "Busiest Station: " << analytics->getBusiestStation() << "\n";
std::cout << "Total Revenue: ₹" << analytics->getTotalRevenue() << "\n";
}
/**
* @brief Example 7: Route Management (Composite Pattern)
*/
void example7_RouteManagement() {
std::cout << "\n=== Example 7: Route Management ===\n";
RouteManager routeManager;
// Create route segments
auto segment1 = std::make_shared<RouteSegment>("DELHI", "GURGAON", 30.0);
auto segment2 = std::make_shared<RouteSegment>("GURGAON", "FARIDABAD", 25.0);
auto segment3 = std::make_shared<RouteSegment>("FARIDABAD", "MATHURA", 45.0);
auto segment4 = std::make_shared<RouteSegment>("MATHURA", "AGRA", 60.0);
// Create complete routes
auto northernRoute = std::make_shared<CompleteRoute>("Delhi-Agra Express Route");
northernRoute->addSegment(segment1);
northernRoute->addSegment(segment2);
northernRoute->addSegment(segment3);
northernRoute->addSegment(segment4);
// Add to route manager
routeManager.addRoute(northernRoute);
// Add distance matrix for pathfinding
routeManager.addDistance("DELHI", "GURGAON", 30.0);
routeManager.addDistance("GURGAON", "FARIDABAD", 25.0);
routeManager.addDistance("FARIDABAD", "MATHURA", 45.0);
routeManager.addDistance("MATHURA", "AGRA", 60.0);
// Display route information
northernRoute->displayRoute();
// Test pathfinding
auto path = routeManager.findShortestPath("DELHI", "GURGAON");
if (!path.empty()) {
std::cout << "Shortest path found: ";
for (const auto& station : path) {
std::cout << station << " ";
}
std::cout << std::endl;
}
// Calculate route distance
std::vector<std::string> testRoute = {"DELHI", "GURGAON", "FARIDABAD"};
double distance = routeManager.calculateRouteDistance(testRoute);
if (distance > 0) {
std::cout << "Route distance (Delhi-Gurgaon-Faridabad): " << distance << " km\n";
}
}
/**
* @brief Example 8: Delay Management System
*/
void example8_DelayManagement() {
std::cout << "\n=== Example 8: Delay Management ===\n";
// Create notification center for delay alerts
auto notificationCenter = std::make_shared<NotificationCenter>();
notificationCenter->addObserver(
std::make_shared<StationMasterNotification>("CONTROL_ROOM")
);
DelayManagementSystem delaySystem(notificationCenter);
// Report various types of delays
std::cout << "Reporting delays...\n";
std::string incident1 = delaySystem.reportDelay(
"EXP001", DelayCategory::TECHNICAL_FAILURE,
20, "Engine overheating detected"
);
std::string incident2 = delaySystem.reportDelay(
"LOC001", DelayCategory::WEATHER,
10, "Heavy rainfall affecting visibility"
);
std::string incident3 = delaySystem.reportDelay(
"HST001", DelayCategory::SIGNAL_PROBLEM,
5, "Signal malfunction at junction"
);
// Display current active delays
delaySystem.displayActiveDelays();
// Update a delay
std::cout << "\nUpdating delay for incident " << incident1 << "...\n";
delaySystem.updateDelay(incident1, 25);
// Resolve a delay
std::cout << "Resolving incident " << incident2 << "...\n";
delaySystem.resolveDelay(incident2);
// Show analytics
delaySystem.displayDelayAnalytics();
}
/**
* @brief Main function demonstrating all examples
*/
int main() {
std::cout << "🚂 Advanced Railway Scheduling System - Usage Examples\n";
std::cout << "=====================================================\n";
try {
example1_BasicStationManagement();
example2_TrainPolymorphism();
example3_NotificationSystem();
example4_SchedulingStrategies();
example5_PassengerManagement();
example6_PerformanceAnalytics();
example7_RouteManagement();
example8_DelayManagement();
std::cout << "\n🎉 All examples completed successfully!\n";
std::cout << "\nNext Steps:\n";
std::cout << "1. Study the source code in src/ directory\n";
std::cout << "2. Run the advanced demo: ./build/bin/advanced_railway_app\n";
std::cout << "3. Check the comprehensive README.md for detailed documentation\n";
std::cout << "4. Explore individual components for your specific use case\n";
} catch (const std::exception& e) {
std::cerr << "❌ Error in examples: " << e.what() << std::endl;
return 1;
}
return 0;
}
/**
* @brief Compilation Instructions:
*
* To compile and run this example:
*
* g++ -std=c++11 -Wall -Wextra -o example_usage example_usage.cpp \
* src/Platform.cpp src/SchedulingStrategy.cpp src/Station.cpp src/Line.cpp
*
* ./example_usage
*
* Or use the Makefile:
* make clean
* g++ -std=c++11 -o build/bin/example_usage example_usage.cpp src/*.cpp
* ./build/bin/example_usage
*/