Skip to content

laxman-gupta1006/Railway_Scheduling_System

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

10 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Advanced Railway Scheduling System

A comprehensive C++11 Railway Management System implementing advanced Object-Oriented Programming and Design (OOPD) concepts. This system provides sophisticated railway operations management with multiple design patterns, performance analytics, passenger management, and real-time scheduling capabilities.

οΏ½ Table of Contents

οΏ½πŸš‚ Advanced Features

Core OOPD Patterns Implemented

  1. Inheritance & Polymorphism - Train class hierarchy with different train types
  2. Strategy Pattern - Multiple scheduling algorithms (FCFS, Priority-based, Optimal)
  3. Observer Pattern - Real-time notification system for passengers and staff
  4. Composite Pattern - Route management with complex route structures
  5. Singleton Pattern - Performance analytics and system monitoring
  6. Factory Pattern - Dynamic pricing strategies for tickets
  7. Template Programming - Generic station ID management

🎯 Key Components

1. Train Management System (Inheritance & Polymorphism)

  • ExpressTrain: High-speed intercity trains with premium pricing
  • LocalTrain: Suburban trains with frequent stops
  • HighSpeedTrain: Modern high-speed rail with advanced features
  • FreightTrain: Cargo transportation with weight-based pricing

2. Intelligent Scheduling (Strategy Pattern)

  • FCFS Scheduling: First Come First Serve algorithm
  • Priority Scheduling: Express trains get priority over local trains
  • Optimal Scheduling: Minimizes delays and maximizes efficiency

3. Real-time Notifications (Observer Pattern)

  • Passenger Notifications: Real-time updates for passengers
  • Station Master Alerts: Operational notifications for staff
  • Maintenance Alerts: System maintenance and technical issues

4. Route Management (Composite Pattern)

  • Route Segments: Individual station-to-station connections
  • Complete Routes: Complex multi-segment journey planning
  • Pathfinding: Shortest route calculation between stations

5. Performance Analytics (Singleton Pattern)

  • Delay Analysis: Track and analyze train delays
  • Revenue Tracking: Monitor financial performance
  • Traffic Analytics: Station and platform utilization metrics
  • Predictive Insights: System performance optimization

6. Passenger Management (Factory Pattern)

  • Dynamic Pricing: Smart pricing based on demand and time
  • Ticket Management: Complete booking lifecycle
  • Passenger Profiles: User registration and management
  • Revenue Optimization: Advanced pricing strategies

7. Delay Management System

  • Incident Tracking: Comprehensive delay cause analysis
  • Mitigation Strategies: Automated resolution suggestions
  • Real-time Updates: Live delay status and notifications
  • Analytics Dashboard: Delay pattern analysis

οΏ½ Installation & Setup

Prerequisites

  • C++ Compiler: GCC 4.8+ or Clang 3.3+ with C++11 support
  • Make: For building the project
  • Git: For cloning the repository (optional)

System Requirements

# Ubuntu/Debian
sudo apt-get install build-essential g++ make

# macOS (with Xcode Command Line Tools)
xcode-select --install

# CentOS/RHEL
sudo yum groupinstall "Development Tools"
sudo yum install gcc-c++

Download & Setup

Option 1: Clone Repository

git clone https://github.com/yourusername/Railway_Scheduling_System.git
cd Railway_Scheduling_System

Option 2: Download ZIP

# Download and extract the ZIP file
wget https://github.com/yourusername/Railway_Scheduling_System/archive/main.zip
unzip main.zip
cd Railway_Scheduling_System-main

Option 3: Use as Library in Your Project

# Copy headers to your project
cp -r src/ /path/to/your/project/include/railway/

# Add to your CMakeLists.txt
include_directories(${PROJECT_SOURCE_DIR}/include/railway)

πŸš€ Quick Start

Build the System

# Create build directories
mkdir -p build/bin build/obj

# Build all components
make all

# Or build specific components
make librailway.a            # Static library
make railway_app             # Original application
make advanced_railway_app    # Advanced features demo
make railway_test           # Unit tests

Quick Test Run

# Run the advanced demo to see all features
./build/bin/advanced_railway_app

# Run unit tests
./build/bin/railway_test

πŸ“– Library Usage Guide

Basic Integration

1. Include Headers

#include "Railwaysystem.h"  // Includes all components

// Or include specific components
#include "Station.h"
#include "Train.h"
#include "NotificationSystem.h"
#include "PassengerManagement.h"

2. Link Library

# Compile your application
g++ -std=c++11 -o your_app your_app.cpp -L. -lrailway

# Or compile with source files directly
g++ -std=c++11 -o your_app your_app.cpp src/*.cpp

Core Usage Patterns

Creating a Basic Railway System

#include "Railwaysystem.h"

int main() {
    // Create stations
    std::vector<Station> stations;
    stations.emplace_back("DELHI");     // String ID
    stations.emplace_back("MUMBAI");    
    
    // Add lines to stations
    auto& delhi = stations[0];
    delhi.addLine("Western Line", 1, 1);    // lineName, lineID, platformNum
    delhi.addLine("Central Line", 2, 2);
    
    // Create trains
    auto expressTrain = std::make_shared<ExpressTrain>("EXP001", "Rajdhani Express");
    auto localTrain = std::make_shared<LocalTrain>("LOC001", "Local Suburban");
    
    // Schedule trains (simplified)
    std::time_t departureTime = createTime(14, 30);  // 2:30 PM
    Platform& platform1 = delhi.getLines()[0].getPlatform();
    
    try {
        platform1.addStoppage(departureTime);
        std::cout << "Train scheduled successfully!" << std::endl;
    } catch (const std::exception& e) {
        std::cout << "Scheduling failed: " << e.what() << std::endl;
    }
    
    return 0;
}

Setting Up Notifications

// Create notification center
auto notificationCenter = std::make_shared<NotificationCenter>();

// Add observers
notificationCenter->addObserver(
    std::make_shared<PassengerNotification>("P001")
);
notificationCenter->addObserver(
    std::make_shared<StationMasterNotification>("DELHI")
);

// Send notifications
notificationCenter->notifyDelayUpdate("EXP001", 15);
notificationCenter->notifyPlatformChange("LOC001", 2, 3);

Using Different Scheduling Strategies

// Create platform
Platform platform(1);
std::vector<std::shared_ptr<Train>> trains = {
    std::make_shared<ExpressTrain>("EXP001", "Express"),
    std::make_shared<LocalTrain>("LOC001", "Local")
};

// Use FCFS scheduling
SchedulingContext scheduler(
    std::unique_ptr<SchedulingStrategy>(new FCFSScheduling())
);
bool success = scheduler.executeScheduling(platform, trains);

// Switch to priority scheduling
scheduler.setStrategy(
    std::unique_ptr<SchedulingStrategy>(new PriorityScheduling())
);

Passenger Management & Ticketing

PassengerManagementSystem pms;

// Register passengers
pms.registerPassenger("P001", "John Doe", "9876543210", "[email protected]");

// Set pricing strategy
pms.setPricingStrategy(
    std::unique_ptr<PricingStrategy>(new DynamicPricing())
);

// Book tickets
std::time_t journeyDate = createTime(14, 30);
std::string ticketID = pms.bookTicket(
    "P001",                              // passenger ID
    "EXP001",                           // train number  
    "DELHI",                            // from station
    "MUMBAI",                           // to station
    journeyDate,                        // journey date
    Ticket::TicketClass::AC_2_TIER,     // class
    1000.0                              // base price
);

// Manage ticket
pms.confirmTicket(ticketID);
auto ticket = pms.findTicket(ticketID);
if (ticket) {
    ticket->displayTicket();
}

Performance Analytics

// Get singleton instance
auto analytics = PerformanceAnalytics::getInstance();

// Record data
analytics->recordDelay("EXP001", 10);
analytics->recordRevenue("DELHI-MUMBAI", 15000.0);
analytics->recordStationTraffic("DELHI");

// Generate reports
analytics->generatePerformanceReport();

// Get specific metrics
double avgDelay = analytics->getSystemWideAverageDelay();
std::string busiestStation = analytics->getBusiestStation();
double totalRevenue = analytics->getTotalRevenue();

Route Management

RouteManager routeManager;

// Create route segments
auto seg1 = std::make_shared<RouteSegment>("DELHI", "GURGAON", 30.0);
auto seg2 = std::make_shared<RouteSegment>("GURGAON", "MUMBAI", 1200.0);

// Create complete route
auto route = std::make_shared<CompleteRoute>("Delhi-Mumbai Express");
route->addSegment(seg1);
route->addSegment(seg2);

// Add to route manager
routeManager.addRoute(route);

// Calculate distances
double totalDistance = route->getTotalDistance();  // 1230.0 km
int stations = route->getTotalStations();          // 3 stations

// Display route information
route->displayRoute();

Delay Management

// Create delay management system
auto notificationCenter = std::make_shared<NotificationCenter>();
DelayManagementSystem delaySystem(notificationCenter);

// Report delays
std::string incidentID = delaySystem.reportDelay(
    "EXP001",                           // train number
    DelayCategory::TECHNICAL_FAILURE,   // category
    20,                                 // delay minutes
    "Engine overheating"                // description
);

// Update delay
delaySystem.updateDelay(incidentID, 25);

// Resolve delay
delaySystem.resolveDelay(incidentID);

// Get analytics
delaySystem.displayDelayAnalytics();
auto activeDelays = delaySystem.getActiveDelays();

πŸ”§ API Reference

Core Classes

Station Class

class Station {
public:
    explicit Station(int id);
    explicit Station(const std::string& id);
    
    void addLine(const std::string& lineName, int lineID, int platformNumber);
    std::vector<Line>& getLines();
    std::string getStationID() const;
    
    static bool isStationIDUnique(const std::string& id);
};

Train Hierarchy

// Base class
class Train {
public:
    virtual double calculateTicketPrice(double distance) const = 0;
    virtual std::string getTrainType() const = 0;
    virtual int getStoppingTime() const = 0;
    virtual double getEffectiveSpeed() const = 0;
    virtual void displayTrainInfo() const;
};

// Derived classes
class ExpressTrain : public Train { /* ... */ };
class LocalTrain : public Train { /* ... */ };
class HighSpeedTrain : public Train { /* ... */ };
class FreightTrain : public Train { /* ... */ };

Platform Class

class Platform {
public:
    explicit Platform(int number);
    
    bool addStoppage(std::time_t time);
    bool addThrough(std::time_t time);
    int getPlatformNumber() const;
    const std::vector<std::pair<std::time_t, bool>>& getSchedule() const;
};

NotificationCenter Class

class NotificationCenter {
public:
    void addObserver(std::shared_ptr<Observer> observer);
    void removeObserver(std::shared_ptr<Observer> observer);
    void notifyObservers(const std::string& message);
    
    void notifyDelayUpdate(const std::string& trainNumber, int delayMinutes);
    void notifyPlatformChange(const std::string& trainNumber, int oldPlatform, int newPlatform);
    void notifyCancellation(const std::string& trainNumber, const std::string& reason);
};

PassengerManagementSystem Class

class PassengerManagementSystem {
public:
    void setPricingStrategy(std::unique_ptr<PricingStrategy> strategy);
    
    bool registerPassenger(const std::string& id, const std::string& name, 
                          const std::string& phone, const std::string& email);
    
    std::string bookTicket(const std::string& passengerID, const std::string& trainNumber,
                          const std::string& from, const std::string& to,
                          std::time_t journeyDate, Ticket::TicketClass ticketClass,
                          double basePrice);
    
    bool cancelTicket(const std::string& ticketID);
    bool confirmTicket(const std::string& ticketID);
    double getTotalRevenue() const;
};

Utility Functions

Time Helper Functions

// Create time from hours and minutes
std::time_t createTime(int hours, int minutes);

// Validate time
bool isValidTime(int hours, int minutes);

Error Handling

The library uses C++ exceptions for error handling:

try {
    station.addLine("Invalid Line", -1, 0);  // Invalid IDs
} catch (const std::runtime_error& e) {
    std::cout << "Error: " << e.what() << std::endl;
}

Common exceptions:

  • std::runtime_error: For operational errors (scheduling conflicts, invalid data)
  • std::invalid_argument: For invalid parameters
  • std::out_of_range: For accessing invalid indices

πŸ’‘ Usage Examples

1. Basic Railway System Setup

#include "Railwaysystem.h"
#include <iostream>

int main() {
    try {
        // Create stations
        std::vector<Station> stations;
        stations.emplace_back("DELHI");
        stations.emplace_back("MUMBAI");
        
        // Add lines to station
        stations[0].addLine("Western Line", 1, 1);
        stations[0].addLine("Central Line", 2, 2);
        
        // Create and schedule trains
        std::time_t departureTime = createTime(14, 30);
        Platform& platform = stations[0].getLines()[0].getPlatform();
        
        platform.addStoppage(departureTime);
        std::cout << "Train scheduled successfully!" << std::endl;
        
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }
    
    return 0;
}

2. Advanced Train Management

// 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<HighSpeedTrain>("HST001", "Vande Bharat"));
trains.push_back(std::make_shared<FreightTrain>("FRT001", "Cargo Express", 500.0));

// Polymorphic behavior demonstration
for (const auto& train : trains) {
    train->displayTrainInfo();
    std::cout << "100km fare: β‚Ή" << train->calculateTicketPrice(100.0) << std::endl;
}

3. Notification System Setup

// 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>()
);

// Send various types of notifications
notificationCenter->notifyDelayUpdate("EXP001", 15);
notificationCenter->notifyPlatformChange("LOC001", 2, 3);
notificationCenter->notifyCancellation("FRT001", "Technical issues");

4. Complete Passenger Management

PassengerManagementSystem pms;

// Register passengers
pms.registerPassenger("P001", "John Doe", "9876543210", "[email protected]");
pms.registerPassenger("P002", "Jane Smith", "9876543211", "[email protected]");

// Set dynamic pricing strategy
pms.setPricingStrategy(
    std::unique_ptr<PricingStrategy>(new DynamicPricing())
);

// Book tickets
std::time_t journeyDate = createTime(14, 30);
std::string ticketID = pms.bookTicket(
    "P001", "EXP001", "DELHI", "MUMBAI", 
    journeyDate, Ticket::TicketClass::AC_2_TIER, 1000.0
);

// Manage tickets
pms.confirmTicket(ticketID);
auto ticket = pms.findTicket(ticketID);
if (ticket) {
    ticket->displayTicket();
}

// Display passenger bookings
pms.displayPassengerBookings("P001");
std::cout << "Total Revenue: β‚Ή" << pms.getTotalRevenue() << std::endl;

5. Performance Analytics Integration

// Get singleton analytics instance
auto analytics = PerformanceAnalytics::getInstance();

// Record various performance metrics
analytics->recordDelay("EXP001", 10);
analytics->recordDelay("EXP001", 15);
analytics->recordStationTraffic("DELHI");
analytics->recordRevenue("DELHI-MUMBAI", 25000.0);
analytics->recordPlatformUtilization("P1", 85.5);

// Generate comprehensive performance report
analytics->generatePerformanceReport();

// Get specific analytics
double avgDelay = analytics->getSystemWideAverageDelay();
std::string busiestStation = analytics->getBusiestStation();
std::string mostDelayed = analytics->getMostDelayedTrain();

🎨 Design Patterns Showcase

Strategy Pattern - Scheduling Algorithms

class SchedulingStrategy {
public:
    virtual bool scheduleTrains(Platform& platform, 
                              const std::vector<std::shared_ptr<Train>>& trains) = 0;
    virtual std::string getStrategyName() const = 0;
};

// Usage
SchedulingContext scheduler(
    std::unique_ptr<SchedulingStrategy>(new PriorityScheduling())
);
bool success = scheduler.executeScheduling(platform, trains);

// Switch strategies at runtime
scheduler.setStrategy(
    std::unique_ptr<SchedulingStrategy>(new OptimalScheduling())
);

Observer Pattern - Real-time Notifications

class NotificationCenter {
    std::vector<std::shared_ptr<Observer>> observers;
public:
    void addObserver(std::shared_ptr<Observer> observer);
    void notifyObservers(const std::string& message);
};

// Concrete observers automatically receive updates
class PassengerNotification : public Observer {
    void update(const std::string& message) override {
        std::cout << "[PASSENGER] " << message << std::endl;
    }
};

Singleton Pattern - Performance Analytics

class PerformanceAnalytics {
private:
    static PerformanceAnalytics* instance;
    PerformanceAnalytics() = default;  // Private constructor
public:
    static PerformanceAnalytics* getInstance() {
        if (instance == nullptr) {
            instance = new PerformanceAnalytics();
        }
        return instance;
    }
};

// Usage - same instance across application
auto analytics1 = PerformanceAnalytics::getInstance();
auto analytics2 = PerformanceAnalytics::getInstance();
// analytics1 == analytics2 (same instance)

Factory Pattern - Dynamic Pricing

class PricingStrategy {
public:
    virtual double calculatePrice(double basePrice, const Ticket& ticket) const = 0;
};

class DynamicPricing : public PricingStrategy {
    double calculatePrice(double basePrice, const Ticket& ticket) const override {
        // Apply dynamic factors (time, demand, season)
        double multiplier = calculateDynamicMultiplier(ticket);
        return basePrice * multiplier;
    }
};

// Factory usage in PassengerManagementSystem
pms.setPricingStrategy(
    std::unique_ptr<PricingStrategy>(new DynamicPricing())
);

πŸ› οΈ Technical Architecture

Project Structure

Railway_Scheduling_System/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ Railwaysystem.h              # Main system header
β”‚   β”œβ”€β”€ Station.h/cpp                # Station management
β”‚   β”œβ”€β”€ Line.h/cpp                   # Railway line operations
β”‚   β”œβ”€β”€ Platform.h/cpp               # Platform scheduling
β”‚   β”œβ”€β”€ Train.h                      # Train class hierarchy
β”‚   β”œβ”€β”€ SchedulingStrategy.h/cpp     # Scheduling algorithms
β”‚   β”œβ”€β”€ NotificationSystem.h         # Observer pattern implementation
β”‚   β”œβ”€β”€ RouteManager.h              # Route planning system
β”‚   β”œβ”€β”€ PerformanceAnalytics.h      # Analytics singleton
β”‚   β”œβ”€β”€ PassengerManagement.h       # Passenger & ticketing system
β”‚   β”œβ”€β”€ DelayManagement.h           # Delay tracking system
β”‚   β”œβ”€β”€ main.cpp                    # Original application
β”‚   └── advanced_main.cpp           # Advanced features demo
β”œβ”€β”€ test/
β”‚   β”œβ”€β”€ railway_test.cpp            # Unit tests
β”‚   └── test.csv                    # Test data
β”œβ”€β”€ build/                          # Build artifacts (generated)
β”‚   β”œβ”€β”€ bin/                        # Executables
β”‚   └── obj/                        # Object files
β”œβ”€β”€ Makefile                        # Build configuration
└── README.md                       # Documentation

Class Relationships

Train (Abstract Base)
β”œβ”€β”€ ExpressTrain
β”œβ”€β”€ LocalTrain  
β”œβ”€β”€ HighSpeedTrain
└── FreightTrain

Station
└── Line
    └── Platform

NotificationCenter (Subject)
└── Observer (Interface)
    β”œβ”€β”€ PassengerNotification
    β”œβ”€β”€ StationMasterNotification
    └── MaintenanceNotification

SchedulingStrategy (Interface)
β”œβ”€β”€ FCFSScheduling
β”œβ”€β”€ PriorityScheduling
└── OptimalScheduling

RouteComponent (Interface)
β”œβ”€β”€ RouteSegment (Leaf)
└── CompleteRoute (Composite)

πŸ§ͺ Building & Testing

Build Requirements

  • C++11 or later
  • GCC 4.8+ or Clang 3.3+
  • Make utility

Build Commands

# Clean previous builds
make clean

# Build static library
make librailway.a

# Build all applications
make all

# Build specific targets
make railway_app              # Original basic application
make advanced_railway_app     # Advanced features demonstration
make railway_test            # Unit test suite

# Direct compilation (alternative)
g++ -std=c++11 -Wall -Wextra -o your_app your_app.cpp src/*.cpp

Running Tests

# Run comprehensive test suite
./build/bin/railway_test

# Run advanced features demo
./build/bin/advanced_railway_app

# Run basic application
./build/bin/railway_app

Test Coverage

The test suite covers:

  • βœ… Station creation and management
  • βœ… Platform scheduling rules
  • βœ… Train scheduling conflicts
  • βœ… Line and platform validation
  • βœ… Edge cases and error conditions

πŸ”§ Advanced Configuration

Custom Train Types

// Create your own train type
class LuxuryTrain : public Train {
public:
    LuxuryTrain(const std::string& number, const std::string& name)
        : Train(number, name, 200, 150.0) {}
    
    double calculateTicketPrice(double distance) const override {
        return distance * 2.5; // Premium pricing
    }
    
    std::string getTrainType() const override { return "Luxury"; }
    int getStoppingTime() const override { return 8; }
    double getEffectiveSpeed() const override { return baseSpeed * 0.97; }
};

Custom Scheduling Strategy

class CustomScheduling : public SchedulingStrategy {
public:
    bool scheduleTrains(Platform& platform, 
                       const std::vector<std::shared_ptr<Train>>& trains) override {
        // Implement your custom scheduling logic
        for (const auto& train : trains) {
            // Your scheduling algorithm here
        }
        return true;
    }
    
    std::string getStrategyName() const override { 
        return "Custom Algorithm"; 
    }
};

Custom Notification Types

class EmailNotification : public Observer {
private:
    std::string emailAddress;
    
public:
    EmailNotification(const std::string& email) : emailAddress(email) {}
    
    void update(const std::string& message) override {
        // Implement email sending logic
        sendEmail(emailAddress, "Railway Alert", message);
    }
    
    std::string getObserverType() const override { return "Email"; }
};

πŸ› Troubleshooting

Common Issues

1. Compilation Errors

# Error: C++11 features not recognized
# Solution: Ensure C++11 flag is used
g++ -std=c++11 -o app app.cpp src/*.cpp

# Error: Missing headers
# Solution: Include path to src directory
g++ -I./src -o app app.cpp src/*.cpp

2. Linking Errors

# Error: Undefined reference to function
# Solution: Link all source files or static library
g++ -o app app.cpp src/Platform.cpp src/Station.cpp src/Line.cpp src/SchedulingStrategy.cpp

# Or use the static library
make librailway.a
g++ -o app app.cpp -L. -lrailway

3. Runtime Errors

// Error: Station ID already exists
// Solution: Check for uniqueness before creating
if (Station::isStationIDUnique("STATION001")) {
    stations.emplace_back("STATION001");
}

// Error: Platform scheduling conflicts
// Solution: Handle exceptions properly
try {
    platform.addStoppage(time);
} catch (const std::runtime_error& e) {
    std::cout << "Scheduling conflict: " << e.what() << std::endl;
}

Performance Optimization

// Use move semantics for large objects
stations.emplace_back(std::move(stationID));

// Reserve vector capacity when size is known
stations.reserve(expectedSize);

// Use const references to avoid copies
void processTrains(const std::vector<std::shared_ptr<Train>>& trains);

πŸ“‹ Best Practices

1. Memory Management

  • Always use smart pointers for dynamic objects
  • Prefer std::make_shared over new
  • Use RAII principles throughout your code

2. Error Handling

  • Always wrap scheduling operations in try-catch blocks
  • Validate input parameters before using them
  • Use meaningful exception messages

3. Performance

  • Reserve vector capacity when size is known
  • Use const references to avoid unnecessary copies
  • Consider using move semantics for large objects

4. Code Organization

  • Keep related functionality in appropriate classes
  • Use the Strategy pattern for varying algorithms
  • Implement Observer pattern for event notifications

5. Thread Safety

  • Be aware that the library is not thread-safe by default
  • Implement your own synchronization when needed
  • Consider using thread-local storage for per-thread data

🀝 Contributing

Development Guidelines

  1. Code Style: Follow existing naming conventions
  2. Documentation: Add comprehensive comments for new features
  3. Testing: Include test cases for new functionality
  4. Error Handling: Implement proper exception handling
  5. Memory Safety: Use smart pointers and RAII

Contribution Process

# Fork the repository
git clone https://github.com/yourusername/Railway_Scheduling_System.git

# Create feature branch
git checkout -b feature/new-feature

# Make changes and test
make clean && make all
./build/bin/railway_test

# Commit and push
git add .
git commit -m "Add new feature: description"
git push origin feature/new-feature

# Create pull request

Areas for Contribution

  • πŸš€ New Train Types: Implement additional train categories
  • πŸ“Š Enhanced Analytics: Add more performance metrics
  • πŸ”„ Scheduling Algorithms: Develop new scheduling strategies
  • 🌐 API Integration: Add REST API capabilities
  • πŸ“± Mobile Support: Create mobile-friendly interfaces
  • πŸ§ͺ Testing: Expand test coverage

πŸ“„ License

This project is available under the MIT License. See LICENSE file for details.

πŸ†˜ Support & Contact

  • Issues: Report bugs via GitHub Issues
  • Documentation: Check this README and inline code comments
  • Examples: See src/advanced_main.cpp for comprehensive usage examples
  • Tests: Refer to test/railway_test.cpp for testing patterns

🌟 Acknowledgments

This advanced Railway Scheduling System demonstrates sophisticated Object-Oriented Programming principles and Design Patterns, making it an excellent showcase of modern C++ software architecture and railway domain expertise.

Design Patterns Implemented:

  • βœ… Inheritance & Polymorphism
  • βœ… Strategy Pattern
  • βœ… Observer Pattern
  • βœ… Singleton Pattern
  • βœ… Factory Pattern
  • βœ… Composite Pattern
  • βœ… Template Programming

Built with passion for clean code architecture and railway systems optimization πŸš‚βœ¨

// Get a reference to a line and its platform
Line& line = station1.getLines()[0];
Platform& platform = line.getPlatform();

// Add trains to the schedule
std::time_t currentTime = std::time(nullptr);

// Add a stoppage train
platform.addStoppage(currentTime);

// Add a through train
platform.addThrough(currentTime + 3600); // 1 hour later

Scheduling Rules

Stoppage Trains

  • Must be scheduled at least 30 minutes apart from other stoppage trains
  • Cannot be scheduled within 30 minutes of a through train

Through Trains

  • Must be scheduled at least 10 minutes apart from other through trains
  • Cannot be scheduled within 10 minutes of a stoppage train

Error Handling

The library uses exception handling to manage errors. Common exceptions include:

try {
    station1.addLine("Red Line", 1, 1);
} catch (const std::runtime_error& e) {
    // Handle duplicate platform numbers or invalid IDs
    std::cerr << "Error: " << e.what() << std::endl;
}

try {
    platform.addStoppage(time);
} catch (const std::runtime_error& e) {
    // Handle scheduling conflicts
    std::cerr << "Scheduling error: " << e.what() << std::endl;
}

Complete Example Program

#include <Railwaysystem.h>
#include <iostream>

int main() {
    try {
        // Create a new station
        Station mainStation("MAIN");
        
        // Add two lines
        mainStation.addLine("Express", 1, 1);
        mainStation.addLine("Local", 2, 2);
        
        // Get the first line and its platform
        Line& expressLine = mainStation.getLines()[0];
        Platform& platform = expressLine.getPlatform();
        
        // Schedule some trains
        std::time_t now = std::time(nullptr);
        platform.addStoppage(now);
        platform.addThrough(now + 3600);
        
        // Print schedule
        for (const auto& schedule : platform.getSchedule()) {
            std::cout << "Train at " << Platform::timeToString(schedule.first)
                     << " - " << (schedule.second ? "Stoppage" : "Through")
                     << std::endl;
        }
        
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return 1;
    }
    
    return 0;
}

Best Practices

  1. Always check for exceptions when adding lines or scheduling trains
  2. Use the getSchedule() method to verify existing schedules
  3. Use timeToString() utility method to convert time_t to readable format
  4. Ensure station IDs are unique across your system
  5. Keep platform numbers unique within each station
  6. Use the consolidated Railwaysystem.h header for simpler projects
  7. Consider using individual headers for more fine-grained control in larger projects

Thread Safety

  • Station ID management is thread-safe due to the use of std::unordered_set
  • Platform scheduling operations are not inherently thread-safe
  • Implement your own mutex locks when accessing platform schedules from multiple threads

Memory Management

The library uses:

  • Smart pointers (std::shared_ptr) for platform management
  • RAII principles throughout
  • STL containers for automatic memory management
  • No raw pointer exposures in public interfaces

Contributing

When contributing to this library, please ensure:

  1. All new features include appropriate error handling
  2. Platform scheduling rules are maintained
  3. Memory management follows RAII principles
  4. New stations maintain ID uniqueness
  5. Header organization follows the established pattern
  6. Thread safety considerations are documented

Building and Testing

# Example build commands
mkdir build
cd build
cmake ..
make

# Running tests (if available)
./tests/railway_tests

Credit

This project was developed with assistance from AI tools, including ChatGPT, to enhance documentation clarity and implementation details.

Support

For bugs, feature requests, or general questions:

  1. Open an issue in the repository
  2. Provide minimum reproducible example
  3. Include your build environment details

About

Assignment 3 OOPD

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published