본문 바로가기
C# 디자인패턴

05# Factory Method 패턴2 Creational Patterns

by NaHyungMin 2019. 5. 23.

 

static void Main(string[] args)

{

    //BuilderExample();

    //FactoryExample();

    //FactoryMethodExample();

 

    FactoryMethodExample2();

 

    //Console.WriteLine("Hello World!");

    Console.ReadKey();

}

 

static void FactoryMethodExample2()

{

    LogManager logManager = new LogManager();

    logManager.AddLog(typeof(Human).Name, new Human());

    logManager.AddLog(typeof(Animal).Name, new Animal());

 

    foreach (string key in logManager.Dictionary.Keys)

    {

        logManager.Dictionary[key].WriteLine();

    }

}

 

main.cs

 

using System;

using System.Collections.Generic;

using System.Text;

 

namespace DesignPatterns.Patterns.FactoryMethod2

{

    public interface ILog

    {

        void WriteLine();

    }

}

 

ILog.cs

using System;

using System.Collections.Generic;

using System.Text;

 

namespace DesignPatterns.Patterns.FactoryMethod2.Logs

{

    public class Animal : ILog

    {

        public void WriteLine()

        {

            Console.WriteLine(string.Format("Name : {0}"this.GetType().Name));

        }

    }

}

 

Animal.cs

 

using System;

using System.Collections.Generic;

using System.Text;

 

namespace DesignPatterns.Patterns.FactoryMethod2.Logs

{

    public class Human : ILog

    {

        public void WriteLine()

        {

            Console.WriteLine(string.Format("Name : {0}"this.GetType().Name));

        }

    }

}

 

Human.cs

 

using System;

using System.Collections.Generic;

using System.Text;

using DesignPatterns.Patterns.FactoryMethod2;

 

namespace DesignPatterns.Patterns.Logs

{

    public class LogManager

    {

        private Dictionary<string, ILog> dictionary = new Dictionary<string, ILog>();

 

        public Dictionary<string, ILog> Dictionary => dictionary;

 

        public void AddLog(string name, ILog log)

        {

            this.Dictionary.Add(name, log);

        }

    }

}

 

Logmanager.cs

 

ILog에 데이터 입력값을 받고, 다른 Class에서 매개변수로 ILog를 받아, 로그를 찍는 방법도 있다.

만드는 방법은 다양함.