GUI 프레임워크에서 제어 로직과 시각적 요소를 분리하는 가상 컨트롤 패턴

전통적 컨트롤 상속의 한계와 대안

WinForms 와 같은 전통적인 GUI 개발 환경에서는 사용자 정의 컨트롤을 생성할 때 `System.Windows.Forms.Control` 또는 `UserControl` 클래스를 직접 상속받는 방식이 주류를 이룹니다. 이는 IDE 설계자에게 익숙하지만, 복잡한 비즈니스 로직과 UI 렌더링 로직이 동일한 객체 내에서 얽히게 되어 유지보수성과 재사용성에 한계가 존재합니다.

public class StandardUserControl : System.Windows.Forms.UserControl
{
    protected override void OnMouseClick(System.EventArgs e)
    {
        // 비즈니스 로직과 UI 이벤트 핸들링이 혼재됨
    }
    
    protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
    {
        // 순수 그래픽 처리 코드가 여기에 위치
    }
}

프록시 기반 가상 컨트롤 아키텍처

위 문제를 해결하기 위해 실제 시각적 위젯 (Visual Widget) 과 그 동작을 제어하는 논리 계층을 분리에 대한 새로운 접근 방식을 도입할 수 있습니다. 이 패턴은 '가상 컨트롤 (Virtual Control)'으로 불리며, 핵심 아이디어는 실제 시스템 컨트롤 위에 추상화된 인터페이스 레이어를 구축하는 것입니다.

이러한 구조에서는 외부 코드나 도메인 로직이 직접 WinForms 의 `Panel`이나 `PictureBox` 같은 구체적인 컨트롤 인스턴스와 결합하지 않습니다. 대신 호스트 컨트롤에 이벤트를 바인딩하여 내부적으로 처리하고, 이를 추상 메서드로 노출함으로써 GUI 플랫폼에 종속되지 않은 비즈니스 로직을 작성할 수 있습니다.

핵심 구현 구조

다음은 실제 컨트롤을 감싸는 기초 클래스 예시입니다. 변수 이름을 변경하고 메서드 호출 흐름을 현대화하여 가독성을 높였습니다.

using System.Drawing;
using System.Windows.Forms;

/// <summary>
/// 실질적인 컨트롤 인스턴스를 참조하며 이벤트를 중개하는 기본 클래스
/// </summary>
public abstract class ProxyControlHandler
{
    private Control _activeHost;
    
    /// <summary>
    /// 현재 연결된 실제 컨트롤 인스턴스
    /// </summary>
    public Control ActiveHost 
    { 
        get => _activeHost; 
        set => SetHost(value); 
    }

    protected ProxyControlHandler()
    {
        InitializeEventHandlers();
    }

    private void InitializeEventHandlers()
    {
        // 이벤트 등록 초기화를 위해 대리자 생성
    }

    private void SetHost(Control newControl)
    {
        if (_activeHost != null)
        {
            UnbindEvents(_activeHost);
        }

        _activeHost = newControl;

        if (_activeHost != null)
        {
            BindEvents(_activeHost);
        }
    }

    private void BindEvents(Control target)
    {
        target.Paint += OnInternalPaint;
        target.MouseMove += OnInternalMouseMove;
        // 기타 키보드 및 마우스 이벤트 구독
    }

    private void UnbindEvents(Control target)
    {
        target.Paint -= OnInternalPaint;
        target.MouseMove -= OnInternalMouseMove;
        // 기존 구독 해제
    }

    private void OnInternalPaint(object sender, PaintEventArgs e)
    {
        InvokeDrawLogic(e.Graphics, e.ClipRectangle);
    }

    private void OnInternalMouseMove(object sender, MouseEventArgs e)
    {
        InvokeMoveLogic(e.X, e.Y);
    }

    /// <summary>
    /// 서브클래스가 오버라이딩하여 화면을 그리는 전용 메서드
    /// </summary>
    protected abstract void InvokeDrawLogic(Graphics g, Rectangle clipRect);

    /// <summary>
    /// 서브클래스가 오버라이딩하여 마우스 이동 로직을 처리하는 전용 메서드
    /// </summary>
    protected abstract void InvokeMoveLogic(int x, int y);

    public void Invalidate()
    {
        if (_activeHost != null) _activeHost.Invalidate();
    }
}

비즈니스 로직과의 통합

이제 개발자는 실제 컨트롤을 상속하는 대신 위의 `ProxyControlHandler`를 상속받아 필요한 기능만 구현하면 됩니다.这使得 코드 구조가 명확해지고, 디자인 타임 (Design Time) 의 안정성을 확보합니다.

public class CustomDataGridControl : ProxyControlHandler
{
    protected override void InvokeDrawLogic(Graphics g, Rectangle clipRect)
    {
        // 그리드 데이터 렌더링 로직
        g.DrawString("Data Grid Header", Font, Brushes.Black, 0, 0);
    }

    protected override void InvokeMoveLogic(int x, int y)
    {
        // 커서 위치 기반 데이터 검증 로직
    }
}

플랫폼 간 상호 운용성

이 패턴의 가장 큰 강점은 비 GUI 컨텍스트에서도 동일한 로직을 사용할 수 있다는 점입니다. 웹 서비스나 백엔드 처리 시에는 별도의 비트맵 이미지를 생성하고 해당 이미지 객체를 통해 `InvokeDrawLogic` 를 호출하여 동일한 그래픽을 출력할 수 있습니다.

public Bitmap GenerateStaticImage(Rectangle bounds)
{
    Bitmap bmp = new Bitmap(bounds.Width, bounds.Height);
    using (Graphics g = Graphics.FromImage(bmp))
    {
        // 실제 폼 컨트롤 없이도 그림 그릴 수 있음
        g.TranslateTransform(bounds.Left, bounds.Top);
        InvokeDrawLogic(g, bounds);
    }
    return bmp;
}

이러한 방식은 리소스 소모가 많은 실제 윈도우 핸들을 최소화하면서도, 동일한 시각 효과와 입력 처리 로직을 다양한 환경 (웹, 데스크톱, 서버 등) 에서 공유할 수 있게 합니다.

태그: C# Windows Forms Proxy Pattern Component Architecture

10월 25일 18:11에 게시됨