# 아키텍처 문서 템플릿 ## 📋 기본 정보 - **프로젝트명**: [프로젝트 이름] - **작성자**: [시스템 아키텍트/기술 리드 이름] - **작성일**: [YYYY-MM-DD] - **버전**: [v1.0] - **상태**: [Draft/Review/Approved/Updated] - **관련 문서**: - PRD: [PRD 문서 링크] - TRD: [TRD 문서 링크] ## 🎯 아키텍처 개요 ### 아키텍처 목표 - **확장성**: 새로운 기능 추가 시 기존 코드 영향 최소화 - **유지보수성**: 코드 가독성과 수정 용이성 - **성능**: Unity 환경에 최적화된 고성능 시스템 - **재사용성**: 모듈 간 결합도 최소화, 응집도 최대화 ### 핵심 아키텍처 원칙 - **관심사 분리**: Presentation, Business, Data 계층 명확 분리 - **의존성 역전**: 인터페이스 기반 의존성 관리 - **단일 책임**: 각 모듈은 하나의 책임만 담당 - **개방-폐쇄 원칙**: 확장에 열려있고 변경에 닫혀있는 구조 ## 🏗️ 시스템 아키텍처 ### 전체 시스템 구조 ``` ┌─────────────────────────────────────────────────────────────┐ │ Unity Game Application │ ├─────────────────────────────────────────────────────────────┤ │ Presentation Layer (UI/View) │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ Game UI │ │ Settings │ │ Shop UI │ │ │ │ Views │ │ Views │ │ Views │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ │ ├─────────────────────────────────────────────────────────────┤ │ Application Layer (ViewModels/Controllers) │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │Game Feature │ │ Settings │ │ Shop │ │ │ │ViewModels │ │ViewModels │ │ViewModels │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ │ ├─────────────────────────────────────────────────────────────┤ │ Domain Layer (Business Logic/Models) │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ Game │ │ Settings │ │ Shop │ │ │ │ Models │ │ Models │ │ Models │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ │ ├─────────────────────────────────────────────────────────────┤ │ Infrastructure Layer (Data Access/External Services) │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │Local Storage│ │ Network │ │ Analytics │ │ │ │ Service │ │ Service │ │ Service │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ │ └─────────────────────────────────────────────────────────────┘ ``` ### Unity 씬 구조 ``` Game Scenes/ ├── Bootstrap.unity # 초기화, DI Container 설정 ├── MainMenu.unity # 메인 메뉴 ├── GamePlay.unity # 핵심 게임플레이 ├── Settings.unity # 설정 화면 └── Loading.unity # 로딩 화면 Persistent Objects/ ├── GameManager (DontDestroyOnLoad) ├── AudioManager (DontDestroyOnLoad) ├── NetworkManager (DontDestroyOnLoad) └── UIManager (DontDestroyOnLoad) ``` ## 🎨 MVVM 아키텍처 패턴 ### MVVM 구조 세부사항 ``` View (MonoBehaviour) ↕ (R3 Observable Binding) ViewModel (C# Class) ↕ (Interface Dependency) Model (ScriptableObject/C# Class) ``` ### 각 계층의 책임 #### View Layer (Unity MonoBehaviour) - **책임**: Unity UI 표시, 사용자 입력 수신 - **금지사항**: 비즈니스 로직, 직접적인 Model 접근 ```csharp public class PlayerHealthView : MonoBehaviour { [SerializeField] private Slider _healthBar; [SerializeField] private Text _healthText; [Inject] private PlayerHealthViewModel _viewModel; private void Start() { // ViewModel과 바인딩만 담당 _viewModel.Health .Subscribe(health => UpdateHealthBar(health)) .AddTo(this); } } ``` #### ViewModel Layer (Pure C#) - **책임**: UI 로직, 데이터 변환, 사용자 액션 처리 - **특징**: Unity에 독립적, 테스트 가능 ```csharp public class PlayerHealthViewModel : IDisposable { [Inject] private IPlayerModel _playerModel; [Inject] private IMessagePublisher<PlayerDiedMessage> _publisher; public ReadOnlyReactiveProperty<float> Health { get; private set; } public ReactiveCommand HealCommand { get; private set; } public void Initialize() { Health = _playerModel.CurrentHealth.ToReadOnlyReactiveProperty(); HealCommand = new ReactiveCommand(); } } ``` #### Model Layer (Data & Business Logic) - **책임**: 게임 데이터, 비즈니스 규칙, 상태 관리 ```csharp [CreateAssetMenu(fileName = "PlayerModel", menuName = "Game/PlayerModel")] public class PlayerModel : ScriptableObject, IPlayerModel { [SerializeField] private float _maxHealth = 100f; public ReactiveProperty<float> CurrentHealth { get; private set; } public ReactiveProperty<bool> IsAlive { get; private set; } public void Initialize() { CurrentHealth = new ReactiveProperty<float>(_maxHealth); IsAlive = CurrentHealth.Select(h => h > 0).ToReactiveProperty(); } } ``` ## 🔧 의존성 주입 아키텍처 (VContainer) ### DI Container 구조 ```csharp public class GameLifetimeScope : LifetimeScope { protected override void Configure(IContainerBuilder builder) { // Singleton Services builder.Register<GameManager>(Lifetime.Singleton); builder.Register<AudioManager>(Lifetime.Singleton); // Models (ScriptableObject) builder.RegisterInstance(_playerModel).As<IPlayerModel>(); builder.RegisterInstance(_gameSettings).As<IGameSettings>(); // ViewModels (Per Feature) builder.Register<PlayerHealthViewModel>(Lifetime.Scoped); builder.Register<InventoryViewModel>(Lifetime.Scoped); // Services builder.Register<IDataService, LocalDataService>(Lifetime.Singleton); builder.Register<INetworkService, UnityNetworkService>(Lifetime.Singleton); } } ``` ### 스코프 계층 구조 ``` Global Scope (Root) ├── Game Scope (게임 세션) │ ├── UI Scope (UI 화면별) │ └── Feature Scope (기능별) └── Scene Scope (씬별) ``` ## 📡 메시징 아키텍처 (MessagePipe) ### 메시징 패턴 설계 ```csharp // 글로벌 이벤트 (게임 전체) public readonly struct GameStartedMessage { } public readonly struct GamePausedMessage { public bool IsPaused; } // 기능별 이벤트 (특정 모듈) public readonly struct PlayerLevelUpMessage { public int NewLevel; } public readonly struct ItemAcquiredMessage { public ItemData Item; } // UI 이벤트 (화면 전환) public readonly struct ShowInventoryMessage { } public readonly struct ShowShopMessage { public ShopType Type; } ``` ### 메시지 플로우 ``` User Input → View → ViewModel → Command → Model → Message → Subscribers ``` ## 🗃️ 데이터 아키텍처 ### 데이터 레이어 구조 ``` Data Layer/ ├── Local Data (PlayerPrefs, JSON Files) │ ├── SaveDataService # 게임 진행 데이터 │ ├── SettingsService # 사용자 설정 │ └── CacheService # 임시 캐시 데이터 ├── Remote Data (Server API) │ ├── UserDataService # 사용자 계정 정보 │ ├── LeaderboardService # 순위 데이터 │ └── ContentService # 게임 콘텐츠 업데이트 └── Static Data (ScriptableObjects) ├── GameDatabase # 게임 설정 데이터 ├── ItemDatabase # 아이템 정보 └── LocalizationDatabase # 다국어 텍스트 ``` ### 데이터 플로우 패턴 ```mermaid graph TD A[User Action] --> B[ViewModel] B --> C[Model Update] C --> D[Data Service] D --> E{Local/Remote?} E -->|Local| F[Local Storage] E -->|Remote| G[Network Service] F --> H[Data Changed Event] G --> H H --> I[Observable Update] I --> J[View Refresh] ``` ## 🎮 게임플레이 아키텍처 ### 게임 상태 관리 ```csharp public enum GameState { Initialize, MainMenu, Loading, Playing, Paused, GameOver, Settings } public class GameStateManager : MonoBehaviour { [Inject] private IMessagePublisher<GameStateChangedMessage> _publisher; private StateMachine<GameState> _stateMachine; private void Initialize() { _stateMachine = new StateMachine<GameState>(); _stateMachine.Configure(GameState.Initialize) .Permit(GameState.MainMenu) .OnEntry(InitializeGame); _stateMachine.Configure(GameState.Playing) .Permit(GameState.Paused) .Permit(GameState.GameOver) .OnEntry(StartGameplay); } } ``` ### 컴포넌트 시스템 ``` GameObject Composition/ ├── Character Controller │ ├── Movement Component │ ├── Health Component │ ├── Inventory Component │ └── Animation Component ├── Weapon System │ ├── Weapon Component │ ├── Projectile Pool │ └── Damage Calculator └── AI System ├── State Machine ├── Behavior Tree └── Pathfinding ``` ## 🎨 UI 아키텍처 ### Canvas 계층 구조 ``` UI Root/ ├── Background Canvas (Sort Order: 0) │ ├── Background Image │ └── Ambient Effects ├── World UI Canvas (Sort Order: 50) │ ├── Damage Numbers │ └── Interaction Prompts ├── Game UI Canvas (Sort Order: 100) │ ├── HUD Elements │ ├── Mini Map │ └── Health/Mana Bars ├── Menu Canvas (Sort Order: 200) │ ├── Main Menu │ ├── Settings Menu │ └── Inventory Menu ├── Popup Canvas (Sort Order: 300) │ ├── Dialog Boxes │ ├── Confirmation Popups │ └── Tooltips └── System Canvas (Sort Order: 999) ├── Loading Screen ├── Debug Info └── FPS Counter ``` ### UI 네비게이션 플로우 ```mermaid graph TD A[Main Menu] --> B[Game Start] A --> C[Settings] A --> D[Shop] B --> E[Game Play] E --> F[Pause Menu] F --> G[Resume] F --> H[Settings] F --> I[Main Menu] E --> J[Inventory] E --> K[Game Over] ``` ## 🔄 이벤트 아키텍처 ### 이벤트 시스템 계층 ``` Event Layer/ ├── Unity Events (Inspector 설정) │ └── UI Button 클릭, Collision 이벤트 등 ├── C# Events (컴포넌트 간) │ └── 같은 GameObject 내 컴포넌트 통신 ├── R3 Observable (MVVM 바인딩) │ └── View-ViewModel 데이터 바인딩 └── MessagePipe (모듈 간) └── 기능 모듈 간 느슨한 결합 통신 ``` ### 이벤트 우선순위 1. **Unity Events**: Inspector 설정, 즉시 처리 2. **C# Events**: 동기 처리, 같은 프레임 내 3. **R3 Observable**: 비동기 UI 업데이트 4. **MessagePipe**: 다음 프레임 처리 가능 ## 🚀 성능 아키텍처 ### 성능 최적화 전략 ``` Performance Architecture/ ├── Memory Management │ ├── Object Pooling (UI Elements, Projectiles) │ ├── Asset Streaming (Addressables) │ └── Garbage Collection Minimization ├── Rendering Optimization │ ├── Batching (Static/Dynamic) │ ├── Culling (Frustum, Occlusion) │ └── LOD System ├── CPU Optimization │ ├── Job System (Parallel Processing) │ ├── Burst Compiler (Math-heavy Operations) │ └── Update Optimization (Cached Components) └── Mobile Optimization ├── Battery Life Consideration ├── Thermal Throttling Prevention └── Network Usage Minimization ``` ### 성능 모니터링 ```csharp public class PerformanceMonitor : MonoBehaviour { [SerializeField] private float _targetFPS = 60f; [SerializeField] private int _maxMemoryMB = 200; private void Update() { MonitorFPS(); MonitorMemory(); MonitorBatteryUsage(); } private void SendPerformanceData() { var data = new PerformanceData { FPS = GetAverageFPS(), MemoryUsage = GetMemoryUsage(), DeviceInfo = SystemInfo.deviceModel }; _analyticsService.SendEvent("performance_data", data); } } ``` ## 🔐 보안 아키텍처 ### 클라이언트 보안 ``` Client Security/ ├── Data Validation │ ├── Input Sanitization │ ├── Range Checks │ └── Type Validation ├── Anti-Cheat │ ├── Critical Data Server Verification │ ├── Behavioral Pattern Analysis │ └── Memory Protection └── Data Protection ├── Save File Encryption ├── Sensitive Data Obfuscation └── Network Communication Encryption ``` ## 🧪 테스트 아키텍처 ### 테스트 계층 구조 ``` Test Architecture/ ├── Unit Tests (Edit Mode) │ ├── Model Logic Tests │ ├── ViewModel Tests │ └── Utility Function Tests ├── Integration Tests (Play Mode) │ ├── MVVM Binding Tests │ ├── Service Integration Tests │ └── Component Interaction Tests ├── Performance Tests │ ├── Memory Leak Tests │ ├── FPS Stability Tests │ └── Load Time Tests └── E2E Tests ├── User Scenario Tests ├── Platform Compatibility Tests └── Network Connectivity Tests ``` ### 테스트 더블 활용 ```csharp // Mock Service for Testing public class MockDataService : IDataService { private Dictionary<string, object> _testData = new(); public async UniTask<T> LoadAsync<T>(string key) { return _testData.ContainsKey(key) ? (T)_testData[key] : default(T); } public async UniTask SaveAsync<T>(string key, T data) { _testData[key] = data; await UniTask.CompletedTask; } } ``` ## 📱 플랫폼별 아키텍처 ### 플랫폼 추상화 ```csharp public interface IPlatformService { void ShowNativeAlert(string title, string message); UniTask<bool> RequestPermission(Permission permission); void OpenAppStore(); void ShareContent(string content); } // Android Implementation public class AndroidPlatformService : IPlatformService { public void ShowNativeAlert(string title, string message) { // Android specific implementation using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) { // Android native dialog implementation } } } // iOS Implementation public class IOSPlatformService : IPlatformService { public void ShowNativeAlert(string title, string message) { // iOS specific implementation #if UNITY_IOS NativeAlert.Show(title, message); #endif } } ``` ## 🔄 배포 아키텍처 ### CI/CD 파이프라인 구조 ``` Deployment Architecture/ ├── Source Control (Git) ├── Build Pipeline │ ├── Code Analysis (SonarQube) │ ├── Unit Tests │ ├── Build Generation │ └── Performance Tests ├── Distribution │ ├── Internal Testing (TestFlight, Internal App Sharing) │ ├── Beta Testing (Public Beta) │ └── Production Release └── Monitoring ├── Crash Reporting (Firebase Crashlytics) ├── Analytics (Firebase Analytics) └── Performance Monitoring ``` ## 🔄 진화 가능한 아키텍처 ### 확장성 고려사항 - **모듈 추가**: 새 기능 모듈 추가 시 기존 코드 변경 최소화 - **플랫폼 확장**: 새로운 플랫폼 지원 시 공통 코드 재사용 - **기술 스택 변경**: 특정 기술 교체 시 인터페이스 기반 분리 - **팀 확장**: 여러 팀이 동시에 개발할 수 있는 구조 ### 버전 관리 전략 ``` Architecture Versioning/ ├── Backward Compatibility │ ├── Interface Versioning │ ├── Data Migration Scripts │ └── Deprecation Warnings ├── Feature Toggles │ ├── A/B Testing Support │ ├── Gradual Rollout │ └── Emergency Rollback └── Documentation Sync ├── Architecture Decision Records (ADR) ├── API Documentation └── Change Log Maintenance ``` ## 📊 아키텍처 메트릭스 ### 품질 지표 - **결합도**: 모듈 간 의존성 수준 - **응집도**: 모듈 내 관련성 수준 - **순환 복잡도**: 코드 복잡성 측정 - **테스트 커버리지**: 테스트 된 코드 비율 ### 성능 지표 - **응답 시간**: 사용자 액션에 대한 반응 속도 - **처리량**: 초당 처리 가능한 작업 수 - **리소스 사용률**: CPU, 메모리, 배터리 사용량 - **안정성**: 크래시 발생률, 오류율 ## 🔄 아키텍처 리뷰 프로세스 ### 정기 검토 사항 - **월간 아키텍처 리뷰**: 구조적 문제점 식별 - **분기별 성능 검토**: 성능 목표 달성도 확인 - **연간 기술 스택 검토**: 새로운 기술 도입 검토 ### 변경 승인 프로세스 1. **아키텍처 변경 제안서** 작성 2. **기술팀 검토** 및 피드백 3. **영향도 분석** 및 리스크 평가 4. **승인** 후 단계별 적용 5. **사후 검토** 및 피드백 --- ## 📚 참고 자료 - [Unity Architecture Best Practices](https://docs.unity3d.com/Manual/BestPracticeGuides.html) - [Clean Architecture by Robert Martin](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html) - [MVVM Pattern Guide](https://docs.microsoft.com/en-us/xamarin/xamarin-forms/enterprise-application-patterns/mvvm) - [Dependency Injection Patterns](https://martinfowler.com/articles/injection.html) --- *최종 업데이트: [YYYY-MM-DD]* *작성자: [시스템 아키텍트 이름]* *버전: v1.0*