리포지토리 패턴 사용하기

    이번에는 리포지토리 인터페이스를 사용하여 리포지토리 클래스 3개에서 상속하는 리포지토리 패턴 예제를 만들어 보겠습니다. 다음 내용을 입력한 후 실행해 보세요.

    저장소 패턴 사용: RepositoryPatternDemo.cs

    using System;
    
    public interface ITableRepository
    {
        string GetAll();
    }
    
    public class TableInMemoryRepository : ITableRepository
    {
        public string GetAll()
        {
            return "인-메모리 데이터베이스 사용";
        }
    }
    
    public class TableSqlRepository : ITableRepository
    {
        public string GetAll() => "SQL Server 데이터베이스 사용";
    }
    public class TableXmlRepository : ITableRepository
    {
        public string GetAll() => "XML 데이터베이스 사용";
    }
    
    class RepositoryPatternDemo
    {
        static void Main()
        {
            //SQL, InMemory, XML 등 넘어오는 값에 따른 인스턴스 생성(저장소 결정)
            string repo = "SQL"; //여기 값을 SQL, InMemory, XML 중 하나로 변경
    
            ITableRepository repository;
            if (repo == "InMemory")
            {
                repository = new TableInMemoryRepository();
            }
            else if (repo == "XML")
            {
                repository = new TableXmlRepository();
            }
            else
            {
                repository = new TableSqlRepository();
            }
    
            Console.WriteLine(repository.GetAll());
        }
    }

    실행 결과

    SQL Server 데이터베이스 사용

    string repo 변수에 저장된 값이 SQL, InMemory, XML에 따라 repository 개체가 서로 다른 클래스의 인스턴스로 생성됩니다.

    이 예제는 나중에 종속성 주입(의존성 주입(dependency injection)) 개념으로 확장됩니다.

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.