Freitag, 18. Mai 2012

Design Patterns - Factory Method C#

Creational -> Factory Method


Das FactoyMethod Pattern definiert ein interface zur Erstellung von Objekten, die selbst entscheiden welche Subklassen Sie instanzieren.

Beispiel:
 class Program
    {
        static void Main(string[] args)
        {

            var cupCakes = new ICupCake[2];

            cupCakes[0] = new CherryCake();

            cupCakes[1] = new StrawberryCake();

            foreach (var cupCake in cupCakes)
            {
                Console.WriteLine(cupCake.GetType().Name);
                List<Fixings> list = cupCake.GetFixings();
                foreach (var fixing in list)
                {
                    Console.WriteLine("-- " + fixing.Name);
                }
            }

        }
    }

    public interface ICupCake
    {
        List<Fixings> GetFixings();
    }

    class CherryCake : ICupCake
    {
        readonly List<Fixings> _fixings = new List<Fixings>();

        public CherryCake()
        {
            _fixings.Add(new Fixings { Name = "Cherries" });
        }

        public List<Fixings> GetFixings()
        {
            return _fixings;
        }
    }

    class StrawberryCake : ICupCake
    {
        readonly List<Fixings> _fixings = new List<Fixings>();

        public StrawberryCake()
        {
            _fixings.Add(new Fixings { Name = "Strawberries" });
        }

        public List<Fixings> GetFixings()
        {
            return _fixings;
        }
    }

    public class Fixings
    {
        public string Name;
    }

Keine Kommentare:

Kommentar veröffentlichen