프로그래밍/C#

[C#] 디자인 패턴 - 실무에서 가장 많이 쓰는 디자인 패턴 3가지 정리 (Singleton, Factory, Command)

큐레이트 2025. 3. 21. 15:24

[C# 디자인 패턴] 실무에서 가장 많이 쓰는 디자인 패턴 3가지 정리

C# 개발을 하다 보면 다양한 디자인 패턴을 접하게 됩니다. 하지만 실무에서는 자주 쓰는 몇 가지 패턴만 집중적으로 활용되곤 합니다.

이 글에서는 C# 실무에서 가장 자주 쓰이는 디자인 패턴 3가지를 소개하고, 구현 코드 예제와 함께 어떤 상황에서 쓰면 좋은지 설명드리겠습니다.


1. 싱글톤 패턴 (Singleton Pattern)

싱글톤 패턴은 하나의 인스턴스만 생성되도록 제한하고, 전역 접근이 가능하게 만드는 디자인 패턴입니다.
주로 설정 클래스, DB 연결 클래스 등에 사용됩니다.


// Thread-safe Singleton 예제
public sealed class ConfigManager
{
    private static readonly Lazy<ConfigManager> instance =
        new Lazy<ConfigManager>(() => new ConfigManager());

    public static ConfigManager Instance => instance.Value;

    private ConfigManager()
    {
        // 초기 설정 로딩
    }

    public string GetValue(string key)
    {
        // 설정 값 반환
        return "설정값";
    }
}

사용 예:


string dbConnection = ConfigManager.Instance.GetValue("DbConnection");

2. 팩토리 패턴 (Factory Pattern)

팩토리 패턴은 객체 생성 로직을 별도의 팩토리 클래스나 메서드로 분리하는 패턴입니다.
복잡한 생성 과정을 캡슐화하고, 의존성을 줄이는 데 유리합니다.


// 인터페이스
public interface INotification
{
    void Send(string message);
}

// 구현 클래스
public class EmailNotification : INotification
{
    public void Send(string message)
    {
        Console.WriteLine($"Email: {message}");
    }
}

// 팩토리
public static class NotificationFactory
{
    public static INotification Create(string type)
    {
        return type switch
        {
            "email" => new EmailNotification(),
            _ => throw new ArgumentException("Unknown type"),
        };
    }
}

사용 예:


var notifier = NotificationFactory.Create("email");
notifier.Send("Hello from factory!");

3. 커맨드 패턴 (Command Pattern)

커맨드 패턴은 요청을 캡슐화하여 실행 취소, 재실행, 큐잉 등을 유연하게 처리할 수 있게 합니다.
주로 UI 버튼 이벤트 처리, Undo/Redo 기능 구현에 많이 사용됩니다.


// 커맨드 인터페이스
public interface ICommand
{
    void Execute();
}

// 구현 클래스
public class SaveCommand : ICommand
{
    public void Execute()
    {
        Console.WriteLine("문서를 저장했습니다.");
    }
}

// 인보커
public class Button
{
    private ICommand command;
    public Button(ICommand command)
    {
        this.command = command;
    }

    public void Click()
    {
        command.Execute();
    }
}

사용 예:


var save = new SaveCommand();
var saveButton = new Button(save);
saveButton.Click();

✅ 마무리

위 3가지 패턴은 C# 실무에서 매우 자주 사용되며, 유지보수성과 확장성을 높여줍니다.
이 외에도 전략 패턴, 옵저버 패턴 등도 실무에서 유용하게 쓰이지만, 우선은 위 세 가지부터 익혀두면 대부분의 프로젝트에서 큰 도움이 됩니다.

앞으로도 C# 실무에 도움이 되는 글들을 계속해서 올릴 예정입니다. 도움이 되셨다면 공감/댓글 부탁드립니다 😊

반응형