A modular Java application simulating printed circuit board (PCB) production and electronic device assembly. This project was developed for the Design Patterns and Clean Code course at Lublin University of Technology (WOiSI, 2025/2026).
The main goal is a practical, end-to-end implementation of all 23 GoF design patterns, SOLID principles, Clean Code standards, functional programming constructs, and compile-time Aspect-Oriented Programming (AspectJ).
The application runs as a console-based simulation driven by high-level process orchestrators in pl.lab.factory.processes, managed by Main.java.
- Order Intake & Configuration – Technical specs, custom component topologies, tolerance thresholds, and production queues.
- Assembly Line (SMT / PCB) – Multi-step hardware assembly (solder paste printing, pick-and-place component mounting, reflow/wave soldering), safety interlocks, and machine cycle monitoring.
- Firmware Provisioning – Flashing microcontrollers with different firmware types (binary, proprietary) via hardware programmers (ST-Link, J-Link), backed by transactional rollback mechanisms.
- Warehouse & Logistics – Partitioned storage sections, access restrictions, multi-layer protective packaging (anti-static bags, cushioning foam), and dispatch queue scheduling.
- Plant Safety System – Hazard detection (smoke sensors, fire gates, sprinkler systems) coordinated by a central mediator with snapshot/restore capabilities.
- Billing & Accounting – Finite-state invoice processing (draft, unpaid, paid, cancelled), flexible discount strategies, and multi-region tax/customs calculations (EU VAT, US Customs).
- Audit & Reporting – Production metrics and cost analysis exported to console or CSV, filtered through an abstract syntax tree query interpreter and cached via proxy.
Every pattern is mapped to a realistic factory requirement rather than generic toy examples.
| Pattern | Application | Key Classes |
|---|---|---|
| Factory Method | Encapsulates the instantiation of concrete PCB board types behind an abstract creator. | BaseBoardFactory, StandardBoardFactory, ManufacturableProduct |
| Simple Factory | Centralizes builder selection based on the target order type. | ProductionOrderFactory |
| Singleton | - SMT machine instances (lazy initialization) - Circuit board printer (thread-safe double-checked locking) - Shared production order backlog (Bill Pugh / static holder idiom) |
Solderer, MounterCircuitPrinterProductionQueue |
| Builder | - Step-by-step assembly of complex board order objects - Fluent interface for engineering specs and compliance certificates |
BaseBoardProductionOrder.BuilderBaseElectronicBoardProductionOrder.BuilderOrderSpecification.Builder |
| Prototype | - Deep copying of base boards for firmware variation tests (via prototype registry) - Memory-efficient shallow cloning of immutable certificates - Duplicating order templates while swapping generated tracking IDs |
BaseBoard.deepCopy(), BoardPrototypesOrderSpecification.clone()ProductionOrder.clone() |
| Pattern | Application | Key Classes |
|---|---|---|
| Adapter | - Integrates legacy string-based console audit systems with BoardReporter- Bridges legacy flat-list warehouse storage with modern partitioned sections - Normalizes diverse firmware representations for flash programmer devices |
LegacyAuditSystemAdapterWarehouseAdapterFirmwareAdapter, HighLevelFirmwareAdapter |
| Composite | - Tree structure for production tasks (individual task vs. batch groups) - Hierarchical warehouse spatial layout (zone -> section -> package item) - Circuit component topology (primitive R/L/C parts and nested component groups) |
ProductionBatch, SingleOrderTaskWarehouseSection, WarehouseItemComponentGroup, BaseComponent |
| Bridge | - Decouples report data selection from output rendering (Console vs. CSV) - Decouples shipping strategy (Standard/Priority) from package box materials - Decouples firmware flashing logic from the physical programming hardware |
ProductionReport & ReportFormatterShippingStrategy & PackageImplementorFirmwareProgrammer & ProgrammingDevice |
| Decorator | - Adds runtime benchmarking and quality control checks to board producers - Dynamically layers ESD wrap and foam protection onto baseline parcel packaging - Wraps assembly machines with warmup cycles and calibration routines |
BoardProducerDecorator, QualityControlDecoratorPackingDecorator, AntiStaticBagDecoratorMachineDecorator, MachineWarmupDecorator |
| Facade | - Unified reporting entry point hiding formatters, filters, and interpreters - High-level interface running the sequence of assembly line steps - Consolidates warehouse inventory lookup, packaging, and carrier dispatch |
ReportingFacadeAssemblyStepManufacturingFacadeShippingFacade |
| Proxy | - Caching proxy storing generated reports to avoid hitting legacy audit services - Protection proxies validating board state and component clearance before machine ops - Access proxy enforcing storage authorization and blocking blacklisted IDs |
CachingBoardReporterProxyPrintingProxy, SolderingProxyWarehouseAccessProxy |
| Flyweight | - Shares immutable compliance certificate instances across specifications - Reuses static electrical definitions (resistance, capacitance) across components - Shares packaging material profiles across warehouse shipping routines |
CertificateFlyweightFactoryComponentDefinitionFactoryPackageFactory |
| Pattern | Application | Key Classes |
|---|---|---|
| Command | - Encapsulates queue mutations into command objects supporting undo/rollback - Buffers and stages shipping commands prior to carrier pickup - Sequences firmware upload operations with error-recovery hooks |
OrderQueueCommand, QueueCommandInvokerShipOrderCommand, ShippingManagerFirmwareCommand, FirmwareCommandInvoker |
| Interpreter | - Evaluates dynamic boolean filter expressions over production reports - Parses compound inventory query rules (status, minimum order volume) - Evaluates board materials to dynamically resolve appropriate line tooling |
AbstractExpression, AndExpression, QuantityExpressionOrderExpression, OrderStatusExpressionBaseProducerExpression, MaterialExpression |
| Iterator | - Traverses orders matching specific criteria without cloning the backing collection - Filters warehouse equipment fleets to locate machines exceeding service hour limits - Stack-based composite iterator flattening deeply nested component hierarchies |
ProductionQueue.StatusIteratorImplEquipmentServiceIteratorCompositeIterator |
| Mediator | - Decouples cross-department events (Production, Warehouse, Billing, Reporting) - Coordinates fire alarm responses (triggers sirens, drops fire doors, arms sprinklers) - Coordinates robotic placement heads and soldering stations along the belt |
CentralControlMediatorWarehouseSafetyCenterFactoryMachineMediator |
| Memento | - Takes snapshots of order states to roll back during production disruptions - Stores safety system configuration snapshots to recover from false alarms - Backs up board firmware images prior to attempting experimental flashing |
OrderStatusMemento, ProductionOrderSafetySystemMemento, SafetyHistoryFirmwareMemento |
| Observer | - Broadcasts order lifecycle changes to external endpoints (ERP sync, email notifications) - Tracks equipment runtime hours and notifies technicians when service limits are hit - Subscribes to hardware assembly events for live metric aggregation |
OrderSubject, ClientEmailNotifier, ErpSystemUpdaterMaintenanceObservable, MaintenanceServiceObservableBoard, ProcessObserver |
| State | - Manages invoice state transitions (Draft -> Unpaid -> Paid / Cancelled)- Toggles storage zone availability ( OpenState vs. emergency LockedState)- Enforces valid operational states on production hardware ( Off, Idle, Running) |
OrderInvoiceState, OrderInvoiceDraftStateSectionState, LockedStateMachineState, RunningState |
| Strategy | - Pluggable pricing and discount calculators (Standard, Bulk, VIP, Holiday) - Outbound sorting strategies for dispatch staging (FIFO vs. Priority first) - Interchangeable manufacturing algorithms (AutoMount vs. ManualMount, Wave vs. Reflow) |
PricingStrategy, BulkPricingStrategy, VipPricingStrategyShippingDispatcher, FifoDispatcher, PriorityFirstDispatcherAssemblingStrategy, AutoMount, WaveSolder |
| Template Method | - Skeleton workflow for invoice dispatch (validation -> rendering -> delivery) - Rigid warehouse inspection routine defining mandatory diagnostic hooks - Standardized report layout structure (header, body, and customizable footer hooks) |
InvoiceDispatcher, B2bApiInvoiceDispatcherMaintenanceProtocol, ForkliftMaintenanceBoardSummaryTemplate, CostReport |
| Visitor | - Applies region-specific tax and customs assessments across heterogenous orders - Inspects queued shipping commands to calculate volumetric priority ratings - Recursively traverses PCB component graphs to tally part counts and total bills of materials |
OrderVisitor, EuVatVisitor, UsaCustomsVisitorCommandVisitor, PriorityCalculatorBoardVisitor, CostVisitor, CountingVisitor |
- Single Responsibility Principle (SRP): Focused classes with single purposes (e.g.,
RevenueCalculatorsolely aggregates financial totals,CsvReportFormatterhandles CSV serializing without data fetching). - Open/Closed Principle (OCP): Logic is open to extension via strategies and parameter maps without modifying core classes (e.g., dynamic loyalty rules in
CustomerLoyaltyService, new equipment servicing viaMaintenanceProtocol). - Liskov Substitution Principle (LSP): All derived strategies, reports, and dispatchers can substitute their abstractions seamlessly without breaking caller expectations.
- Interface Segregation Principle (ISP): Fat interfaces were decomposed into fine-grained contracts (e.g.,
WarehouseServiceFatsplit intoWarehouseManagementServiceandWarehouseReportingService; PCB components separated intoPositionable,SignalProcessor, andVisitable). - Dependency Inversion Principle (DIP): High-level coordinators depend strictly on abstractions rather than concrete classes (e.g.,
PricingStrategy,PackageImplementor,ProgrammingDevice). - Clean Code Standards:
- Small methods (under 20 lines) focused on a single responsibility.
- Stepdown rule (reading top-to-bottom, from high-level orchestrators to detail methods).
- Maximum 3 parameters per method (context parameter objects like
OrderContext). - No magic numbers (
private static finalconstants). - Explicit business exceptions instead of integer return codes.
- Strict DRY (reusable logic extracted to abstract builders and helper bases).
- Custom
@FunctionalInterfacedeclarations:OrderCostCalculator,OrderDescriptionFormatter,OrderStatusChecker. - Declarative Stream API pipelines: filtering, custom sorting, entity extraction (
map), deduplication (distinct), and numeric aggregations (mapToDouble,sum,max). - Functional composition using standard
java.util.functioncombinators (Predicate.and(),Predicate.negate(),Function.andThen()).
Compile-time aspect weaving managed by aspectj-maven-plugin:
FactoryLoggingAspect: Logs process lifecycle start and finish events (@Before/@Afteronexecute()methods).OrderValidationAspect: Intercepts calls tostoreOrder()inWarehouseServiceto reject malformed orders (@Before).PerformanceMonitoringAspect: Intercepts targeted methods with@Around(ProceedingJoinPoint) to benchmark execution duration in milliseconds.
Unit test suite implemented with JUnit 5 and Mockito:
OrderInvoiceDraftStateTest: Validates state transition rules, operation locks, and mocking interactions for invoice processing.EuVatVisitorTest: Validates tax and surcharge calculations across mock order structures.ProductionQueueTest: Tests queue mutations, order retrieval, and undo command integrity.QuantityExpressionTest: Tests grammar AST resolution and boolean evaluation under different context filters.
- Java: JDK 21+
- Maven: 3.8+
# Compile and weave AspectJ aspects
mvn clean compile
# Run the factory simulation
mvn exec:java
# Run test suite
mvn testsrc/main/java/pl/lab/factory/
├── assemblyline/ # Production machines, SMT strategies, safety decorators
├── aspects/ # AspectJ aspects (logging, profiling, argument assertions)
├── components/ # Circuit board parts (composite R/L/C, flyweights)
├── electronicboards/ # Smart boards, firmware modules, hardware programmers
├── functional/ # Custom functional interfaces
├── manufacturing/ # Board factories and order processor pipelines
├── mediator/ # Cross-department central mediator and colleagues
├── orders/ # Orders, builders, invoices, state, memento, visitors
├── pcbboards/ # Physical PCB models, lifecycle observers, report templates
├── processes/ # Step-by-step simulation runners (FactoryContext)
├── reporting/ # Report generators, legacy audit adapters, query interpreter
├── safetymediator/ # Plant safety mediator, fire alarms, sensors
├── scheduling/ # Composite task batches and order execution units
└── warehouse/ # Storage management, packaging decorators, dispatch strategies