재우니의 블로그



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryPatternSample {
  class Program {
    interface ILogger {
      void Log(string Message);
    }

    enum LoggerType {
      File,
      Database,
      EventViewer
    }

    class FileLogger: ILogger {
      public void Log(string Message) {
        Console.WriteLine("{0} - Logged in File.", Message);
      }
    }

    class DatabaseLogger: ILogger {
      public void Log(string Message) {
        Console.WriteLine("{0} - Logged in Database.", Message);
      }
    }

    class EventViewerLogger: ILogger {
      public void Log(string Message) {
        Console.WriteLine("{0} - Logged in EventViewer.", Message);
      }
    }

    class LoggerFactory {
      public static ILogger Get(LoggerType type) {
        switch (type) {
        case LoggerType.Database:
          return new DatabaseLogger();
        case LoggerType.EventViewer:
          return new EventViewerLogger();
        case LoggerType.File:
        default:
          return new FileLogger();
        }
      }
    }

    static void Main(string[] args) {
      ILogger logger1 = LoggerFactory.Get(LoggerType.Database);
      logger1.Log("Message from Main");

      ILogger logger2 = LoggerFactory.Get(LoggerType.File);
      logger2.Log("Message from Main");

      ILogger logger3 = LoggerFactory.Get(LoggerType.EventViewer);
      logger3.Log("Message from Main");

      Console.ReadKey();

      /*Output
      Message from Main - Logged in Database.
      Message from Main - Logged in File.
      Message from Main - Logged in EventViewer.
      */
    }
  }
}