This repository contains the complete implementation of the HC-2025-26 coding exercises, featuring 6 design patterns and a mini project built with TypeScript. The solution demonstrates professional software development practices, SOLID principles, and clean architecture.
Behavioral Patterns (2)
- Observer Pattern - Stock price notification system with multiple observer types
- Strategy Pattern - Payment processing with interchangeable payment methods
Creational Patterns (2)
- Singleton Pattern - Database connection manager with thread safety
- Factory Pattern - Shape creation system with multiple geometric types
Structural Patterns (2)
- Adapter Pattern - Media player with format compatibility adapters
- Proxy Pattern - File system with role-based access control
A comprehensive CRUD console application implementing:
- Singleton Pattern - Schedule Manager (single instance)
- Factory Pattern - Task creation with templates
- Observer Pattern - Conflict detection and notifications
- Node.js 18+
- npm or yarn
- TypeScript 5.0+
# Clone the repository
git clone <repository-url>
cd hc-2025-26-coding-exercises
# Install dependencies
npm install
# Build the project
npm run build
# Run the complete application
npm start
# Run individual exercises
npm run exercise1 # Design patterns only
npm run exercise2 # Schedule organizer only
# Development mode with hot reload
npm run dev
// Run all design pattern demonstrations
import { runExercise1 } from './src/exercise1';
runExercise1();
// Or run specific patterns
import { demonstrateObserverPattern } from './src/exercise1/behavioral/ObserverPattern';
demonstrateObserverPattern();
// Create and run the schedule organizer
import { AstronautScheduleOrganizer } from './src/exercise2';
const app = new AstronautScheduleOrganizer();
app.run();
// Or use individual components
import { ScheduleManager, TaskFactory, Priority } from './src/exercise2';
const manager = ScheduleManager.getInstance();
const task = manager.addTask(
"EVA Preparation",
"09:00",
"11:00",
Priority.HIGH
);
- β SOLID Principles - Single responsibility, Open/closed, etc.
- β Design Patterns - 6+ patterns implemented correctly
- β Error Handling - Comprehensive try/catch with custom errors
- β Logging System - Structured logging with multiple levels
- β Input Validation - Robust validation at all entry points
- β Type Safety - Full TypeScript type checking
- β Performance - Optimized algorithms and data structures
- β CRUD Operations - Create, Read, Update, Delete tasks
- β Conflict Detection - Automatic overlap detection
- β Real-time Notifications - Observer-based event system
- β Task Templates - Pre-defined astronaut activity templates
- β Priority Management - High/Medium/Low priority filtering
- β Time Management - Robust time parsing and validation
- β Statistics & Analytics - Comprehensive reporting
Use Case: Stock price tracking with multiple notification channels
Components:
StockPriceTracker
(Subject) - Manages stock pricesEmailNotifier
,SMSNotifier
,DashboardNotifier
(Observers)
Features:
- Dynamic subscription/unsubscription
- Multiple observer types
- Automatic notification on price changes
- Loose coupling between components
const tracker = new StockPriceTracker();
tracker.addObserver(new EmailNotifier("investor@example.com"));
tracker.updateStockPrice("AAPL", 150.25); // Notifies all observers
Use Case: E-commerce payment processing with multiple payment methods Components:
PaymentProcessor
(Context)CreditCardPayment
,PayPalPayment
,BankTransferPayment
(Strategies)
Features:
- Runtime algorithm selection
- Easy addition of new payment methods
- Encapsulated payment logic
- Error handling per payment type
const processor = new PaymentProcessor(new CreditCardPayment("4532...", "123", "12/25"));
processor.executePayment(99.99);
processor.setPaymentStrategy(new PayPalPayment("user@example.com", "password"));
ποΈ Singleton Pattern - Database Connection
#### ποΈ Singleton Pattern - Database ConnectionUse Case: Database connection management with single instance
Features:
- Thread-safe singleton implementation
- Connection pooling simulation
- Query execution tracking
- Automatic reconnection handling
const db1 = DatabaseConnection.getInstance();
const db2 = DatabaseConnection.getInstance();
console.log(db1 === db2); // true - same instance
Factory Pattern - Shape Creator
Use Case: Geometric shape creation with different types
Use Case: Geometric shape creation with different types Features:
- Centralized object creation
- Type-safe shape creation
- Template-based shape generation
- Automatic area/perimeter calculations
const factory = GeometricShapeFactory.getInstance();
const circle = factory.createShape(ShapeType.CIRCLE, [5], "red");
const rectangle = factory.createShape(ShapeType.RECTANGLE, [4, 6], "blue");
π΅ Adapter Pattern - Media Player
Use Case: Media player supporting multiple audio formats
Components:
AudioPlayer
(Target)MediaAdapter
(Adapter)VlcPlayer
,Mp3Player
,WavPlayer
(Adaptees)
Features:
- Format compatibility layer
- Legacy system integration
- Unified interface for different formats
- Play history tracking
const player = new AudioPlayer();
player.play("mp3", "song.mp3"); // Built-in support
player.play("vlc", "movie.vlc"); // Uses adapter
player.play("wav", "audio.wav"); // Uses adapter
π‘οΈ Proxy Pattern - File Access Control
Use Case: File system with role-based access control
Components:
FileSystemProxy
(Proxy)RealFileSystem
(Subject)User
with different roles (Admin, User, Guest)
Features:
- Role-based permissions
- Access logging
- Security validation
- Sensitive file protection
const fileSystem = new FileSystemProxy();
fileSystem.setCurrentUser(new User("Alice", UserRole.ADMIN));
fileSystem.readFile("config.ini"); // Allowed for admin
fileSystem.setCurrentUser(new User("Bob", UserRole.GUEST));
fileSystem.writeFile("test.txt", "content"); // Denied for guest
Task Management
- β Add custom tasks with time validation
- β Add tasks from predefined templates
- β Update task descriptions, priority, and status
- β Remove tasks with conflict resolution
- β Mark tasks as completed/in-progress
Conflict Detection
- β Real-time overlap detection
- β Automatic conflict notifications
- β Resolution suggestions
- β Priority-based conflict analysis
Task Templates
- π Routine: System checks, daily logs
- π§ Maintenance: Equipment servicing, repairs
- π§ͺ Experiment: Scientific activities, research
- πͺ Exercise: Physical fitness, health activities
- π‘ Communication: Earth contact, briefings
- π¨ Emergency: Safety drills, emergency procedures
// Create schedule manager
const manager = ScheduleManager.getInstance();
// Add tasks with different priorities
manager.addTask("Morning Exercise", "07:00", "08:00", Priority.HIGH);
manager.addTask("Science Experiment", "09:00", "11:00", Priority.MEDIUM);
manager.addTask("Communication with Earth", "14:00", "15:00", Priority.HIGH);
// View tasks by priority
const highPriorityTasks = manager.viewTasksByPriority(Priority.HIGH);
// Detect conflicts
const conflicts = manager.checkForConflicts(taskId);
// Input validation
try {
manager.addTask("", "25:00", "26:00", Priority.HIGH);
} catch (error) {
console.log(error.message); // "Invalid time format"
}
// Conflict detection
try {
manager.addTask("Overlapping Task", "07:30", "08:30", Priority.LOW);
} catch (error) {
// Task added but conflicts reported via observers
}
// Resource management
try {
const task = manager.getTaskById(999);
} catch (error) {
console.log(error.message); // "Task not found: ID 999"
}
Principle | Implementation |
---|---|
Single Responsibility | Each class has one clear purpose (Task, TaskFactory, ScheduleManager) |
Open/Closed | Easy to extend with new task types, observers, payment methods |
Liskov Substitution | All observers/strategies are interchangeable |
Interface Segregation | Focused interfaces (PaymentStrategy, ScheduleObserver) |
Dependency Inversion | Depends on abstractions, not concrete implementations |
This project is licensed under the MIT License - see the LICENSE file for details.