KOS Decorator Pattern Architecture

The Framework Access Pattern

KOS uses decorators as the primary interface to framework services – similar to Spring’s annotation-driven approach or .NET’s attribute system. Rather than manually configuring services through imperative code, KOS developers use declarative decorators to access logging, configuration, event handling, async operations, and more.

This decorator-driven architecture eliminates boilerplate while providing consistent, discoverable access to framework capabilities.

Declarative Service Integration

Traditional Service Integration

In traditional frameworks, accessing services requires explicit setup, manual lifecycle management, and repetitive configuration:

// Manual service wiring (traditional approach)
class DeviceController {
  private logger: Logger;
  private eventBus: EventBus;
  private configService: ConfigService;
  private subscriptions: Subscription[] = [];
  constructor() {
    // Manual service initialization
    this.logger = LoggerFactory.create("DeviceController");
    this.eventBus = EventBusFactory.getInstance();
    this.configService = new ConfigService();
    // Manual event subscription
    const sub = this.eventBus.subscribe("device.status", this.handleStatus.bind(this));
    this.subscriptions.push(sub);
  }
  destroy() {
    // Manual cleanup required
    this.subscriptions.forEach(sub => sub.unsubscribe());
  }
}

KOS Decorator Approach

KOS eliminates this boilerplate through declarative decorators that automatically inject services and handle lifecycle:

// Declarative service integration (KOS approach)
@kosModel({ modelTypeId: "device-controller", singleton: false })
@kosLoggerAware()
export class DeviceController {
  // Logger automatically injected and configured
  // Event subscriptions automatically managed
  // Configuration properties automatically synchronized
  @kosTopicHandler({ topic: "device.status" })
  handleStatus(payload: DeviceStatus): void {
    this.logger.info(`Device status: ${payload.status}`);
    // Subscription and cleanup handled automatically
  }
}

Framework Service Categories

KOS decorators provide access to several categories of framework services:

Foundation Services

  • Model Definition: @kosModel – Establishes model identity and lifecycle
  • Logging: @kosLoggerAware – Structured, contextual logging
  • Dependencies: @kosDependency – Automatic dependency injection

Data & State Management

  • Configuration: @kosConfigProperty – Reactive configuration binding
  • State Properties: @kosStateProp – Reactive state with validation
  • Model Relationships: @kosChild, @kosCompanion – Hierarchical relationships

Communication & Events

  • Event Handling: @kosTopicHandler – WebSocket message routing
  • HTTP Integration: @Get, @Post, etc. – REST API endpoints
  • Reactive Effects: @kosModelEffect – Side effect management

Advanced Capabilities

  • Async Operations: @kosFutureAware, @kosFuture – Long-running operation management
  • Trouble Management: @kosTroubleAware – Automatic trouble detection and reporting
  • Collections: @kosContainerAware – Model collection management with automatic capacity management for memory safety
  • Context Injection: @kosContext – Dependency and context access

Decorator Composition & Layering

Additive Capabilities

Decorators compose naturally – each adds specific capabilities without interfering with others:

@kosModel({ modelTypeId: "comprehensive-service", singleton: false })     // Foundation
@kosLoggerAware()                      // + Logging
@kosFutureAware()                      // + Async operations
@kosTroubleAware()                     // + Trouble detection
@kosContainerAware<DeviceModel>()      // + Collection management
export class ComprehensiveService {
  // All capabilities available simultaneously
  // No conflicts or configuration complexity
}

Consistent Developer Experience

Every KOS service follows the same decorator pattern:

  • Discoverable: IDE auto-completion reveals available services
  • Consistent: Same patterns across all framework features
  • Type-Safe: TypeScript interfaces provide compile-time validation
  • Self-Documenting: Decorator names clearly indicate functionality

Architectural Benefits

Separation of Concerns

Decorators separate “what capabilities I need” from “how to implement those capabilities”:

  • Business Logic: Focused on domain problems
  • Framework Services: Handled declaratively through decorators
  • Configuration: Externalized through decorator parameters
  • Lifecycle: Automatically managed by the framework

Framework Evolution

The decorator pattern allows KOS to evolve framework services without breaking existing code:

  • New Services: Added as new decorators without affecting existing models
  • Enhanced Features: Decorator parameters can be extended while maintaining backward compatibility
  • Performance Optimizations: Framework can optimize service injection without developer changes

As part of this evolution, KOS has migrated from separate registration files to integrated decorator-based registration. The @kosModel decorator now automatically injects a static Registration property, eliminating boilerplate registration code while maintaining the same factory interface for model instantiation. This change represents the framework’s maturation from manual service wiring to fully declarative capability definition.

Team Productivity

Decorators reduce cognitive load and accelerate development:

  • Less Boilerplate: Focus on business logic instead of framework wiring
  • Consistent Patterns: Same approach across all framework services
  • Reduced Errors: Automatic lifecycle management eliminates common mistakes
  • Better Onboarding: New developers learn one pattern that applies everywhere

Design Philosophy

Convention Over Configuration

KOS decorators embody “convention over configuration”:

  • Smart Defaults: Most decorators work with minimal or no configuration
  • Progressive Enhancement: Additional parameters available when needed
  • Automatic Wiring: Framework handles service connections automatically

Explicit Over Implicit

While decorators reduce boilerplate, they maintain explicitness:

  • Visible Dependencies: Decorators clearly show what services a model uses
  • Intentional Design: Developers explicitly choose which capabilities to add
  • Predictable Behavior: Decorator presence guarantees specific functionality

Integration with Traditional Patterns

KOS decorators complement rather than replace traditional design patterns:

  • Dependency Injection: Enhanced through @kosDependency and @kosContext
  • Observer Pattern: Streamlined through @kosTopicHandler and @kosModelEffect
  • Command Pattern: Simplified through @kosFuture operations
  • Facade Pattern: Enabled through @kosCompanion proxying

Framework Access Evolution

The decorator pattern represents KOS’s evolution toward mature framework design:

  1. Early KOS: Manual service access and configuration
  2. Current KOS: Decorator-driven service integration
  3. Future KOS: AI-assisted decorator recommendation and optimization

This evolution mirrors other successful frameworks that have moved toward annotation/decorator-driven architectures as they mature.

Conclusion

The KOS decorator pattern transforms framework interaction from imperative configuration to declarative capability definition. This architectural choice:

  • Reduces Complexity: Eliminates service wiring boilerplate
  • Improves Consistency: Same patterns across all framework features
  • Enhances Productivity: Developers focus on business logic
  • Enables Evolution: Framework can enhance services without breaking changes

Like Spring’s annotations or .NET’s attributes, KOS decorators provide the foundation for scalable, maintainable applications by making framework capabilities both powerful and approachable.