Skip to content

Jenisbarad/Project_Design_Pattern

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

HC-2025-26 Coding Exercises

TypeScript Implementation of Design Patterns and Mini Project

Project Overview

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.

Architecture & Design Patterns

Exercise 1: Design Pattern Showcase

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

Exercise 2: Astronaut Daily Schedule Organizer

A comprehensive CRUD console application implementing:

  • Singleton Pattern - Schedule Manager (single instance)
  • Factory Pattern - Task creation with templates
  • Observer Pattern - Conflict detection and notifications

Quick Start

Prerequisites

  • Node.js 18+
  • npm or yarn
  • TypeScript 5.0+

Installation & Setup

# 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

Alternative Run Commands

# Run individual exercises
npm run exercise1    # Design patterns only
npm run exercise2    # Schedule organizer only

# Development mode with hot reload
npm run dev

Usage Examples

Exercise 1: Design Patterns

// Run all design pattern demonstrations
import { runExercise1 } from './src/exercise1';
runExercise1();

// Or run specific patterns
import { demonstrateObserverPattern } from './src/exercise1/behavioral/ObserverPattern';
demonstrateObserverPattern();

Exercise 2: Schedule Organizer

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

πŸ”§ Key Features

Technical Excellence

  • βœ… 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

Functional Features

  • βœ… 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

Design Pattern Details

πŸ” Observer Pattern - Stock Price Notifier

Use Case: Stock price tracking with multiple notification channels

Components:

  • StockPriceTracker (Subject) - Manages stock prices
  • EmailNotifier, 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
#### πŸ’³ Strategy Pattern - Payment Processing

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 Connection

Use 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

🏭 Factory Pattern - Shape Creator

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

πŸš€ Exercise 2: Astronaut Schedule Organizer

Core Features

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

Sample Usage Scenarios

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

πŸ§ͺ Testing & Quality Assurance

Error Handling Examples

// 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"
}

🎯 SOLID Principles Implementation

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

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published