1. 程式人生 > >Design Pattern - Factory Method(C#)

Design Pattern - Factory Method(C#)

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow

也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!

               

Definition

Define an interface for creating an object, but let sub classes decide which class to instantiate. Factory Method lets a class defer instantiation to sub classes.

Participants

    The classes and/or objects participating in this pattern are:

  • Product (Page)
    • Defines the interface of objects the factory method creates
  • ConcreteProduct (SkillsPage, EducationPage, ExperiencePage)
    • Implements the Product interface
  • Creator (Document)
    • Declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object.
    • May call the factory method to create a Product object.
  • ConcreteCreator
     (Report, Resume)
    • Overrides the factory method to return an instance of a ConcreteProduct.

Sample Code in C#


This structural code demonstrates the Factory Method offering great flexibility in creating different objects. The abstract class may provide a default object, but each subclass can instantiate an extended version of the object.

// --------------------------------------------------------------------------------------------------------------------// <copyright company="Chimomo's Company" file="Program.cs">// Respect the work.// </copyright>// <summary>// Structural Factory Method Design Pattern.// </summary>// --------------------------------------------------------------------------------------------------------------------namespace CSharpLearning{    using System;    using System.Linq;    /// <summary>    /// Startup class for Structural Factory Method Design Pattern.    /// </summary>    internal static class Program    {        #region Methods        /// <summary>        /// Entry point into console application.        /// </summary>        private static void Main()        {            // An array of creators            var creators = new Creator[2];            creators[0] = new ConcreteCreatorA();            creators[1] = new ConcreteCreatorB();            // Iterate over creators and create products            foreach (Product product in creators.Select(creator => creator.FactoryMethod()))            {                Console.WriteLine("Created {0}", product.GetType().Name);            }        }        #endregion    }    /// <summary>    /// The 'Product' abstract class    /// </summary>    internal abstract class Product    {    }    /// <summary>    /// A 'ConcreteProduct' class    /// </summary>    internal class ConcreteProductA : Product    {    }    /// <summary>    /// A 'ConcreteProduct' class    /// </summary>    internal class ConcreteProductB : Product    {    }    /// <summary>    /// The 'Creator' abstract class    /// </summary>    internal abstract class Creator    {        #region Public Methods and Operators        /// <summary>        /// The factory method.        /// </summary>        /// <returns>        /// The <see cref="Product"/>.        /// </returns>        public abstract Product FactoryMethod();        #endregion    }    /// <summary>    /// A 'ConcreteCreator' class    /// </summary>    internal class ConcreteCreatorA : Creator    {        #region Public Methods and Operators        /// <summary>        /// The factory method.        /// </summary>        /// <returns>        /// The <see cref="Product"/>.        /// </returns>        public override Product FactoryMethod()        {            return new ConcreteProductA();        }        #endregion    }    /// <summary>    /// A 'ConcreteCreator' class    /// </summary>    internal class ConcreteCreatorB : Creator    {        #region Public Methods and Operators        /// <summary>        /// The factory method.        /// </summary>        /// <returns>        /// The <see cref="Product"/>.        /// </returns>        public override Product FactoryMethod()        {            return new ConcreteProductB();        }        #endregion    }}// Output:/*Created ConcreteProductACreated ConcreteProductB*/

This real-world code demonstrates the Factory Method offering flexibility in creating different documents. The derived Document classes Report and Resume instantiate extended versions of the Document class. Here, the Factory Method is called in the constructor of the Document base class.

// --------------------------------------------------------------------------------------------------------------------// <copyright company="Chimomo's Company" file="Program.cs">// Respect the work.// </copyright>// <summary>// Real-World Factory Method Design Pattern.// </summary>// --------------------------------------------------------------------------------------------------------------------namespace CSharpLearning{    using System;    using System.Collections.Generic;    /// <summary>    /// Startup class for Real-World Factory Method Design Pattern.    /// </summary>    internal static class Program    {        #region Methods        /// <summary>        /// Entry point into console application.        /// </summary>        private static void Main()        {            // Note: constructors call Factory Method            var documents = new Document[2];            documents[0] = new Resume();            documents[1] = new Report();            // Display document pages            foreach (Document document in documents)            {                Console.WriteLine("\n" + document.GetType().Name + "--");                foreach (Page page in document.Pages)                {                    Console.WriteLine(" " + page.GetType().Name);                }            }        }        #endregion    }    /// <summary>    /// The 'Product' abstract class    /// </summary>    internal abstract class Page    {    }    /// <summary>    /// A 'ConcreteProduct' class    /// </summary>    internal class SkillsPage : Page    {    }    /// <summary>    /// A 'ConcreteProduct' class    /// </summary>    internal class EducationPage : Page    {    }    /// <summary>    /// A 'ConcreteProduct' class    /// </summary>    internal class ExperiencePage : Page    {    }    /// <summary>    /// A 'ConcreteProduct' class    /// </summary>    internal class IntroductionPage : Page    {    }    /// <summary>    /// A 'ConcreteProduct' class    /// </summary>    internal class ResultsPage : Page    {    }    /// <summary>    /// A 'ConcreteProduct' class    /// </summary>    internal class ConclusionPage : Page    {    }    /// <summary>    /// A 'ConcreteProduct' class    /// </summary>    internal class SummaryPage : Page    {    }    /// <summary>    /// A 'ConcreteProduct' class    /// </summary>    internal class BibliographyPage : Page    {    }    /// <summary>    /// The 'Creator' abstract class    /// </summary>    internal abstract class Document    {        #region Fields        /// <summary>        /// The pages.        /// </summary>        private List<Page> pages = new List<Page>();        #endregion        // Constructor calls abstract Factory method        #region Constructors and Destructors        /// <summary>        /// Initializes a new instance of the <see cref="Document"/> class.        /// </summary>        protected Document()        {            this.CreatePages();        }        #endregion        #region Public Properties        /// <summary>        /// Gets the pages.        /// </summary>        public List<Page> Pages        {            get            {                return this.pages;            }        }        #endregion        // Factory Method        #region Public Methods and Operators        /// <summary>        /// The create pages.        /// </summary>        public abstract void CreatePages();        #endregion    }    /// <summary>    /// A 'ConcreteCreator' class    /// </summary>    internal class Resume : Document    {        // Factory Method implementation        #region Public Methods and Operators        /// <summary>        /// The create pages.        /// </summary>        public override void CreatePages()        {            this.Pages.Add(new SkillsPage());            this.Pages.Add(new EducationPage());            this.Pages.Add(new ExperiencePage());        }        #endregion    }    /// <summary>    /// A 'ConcreteCreator' class    /// </summary>    internal class Report : Document    {        // Factory Method implementation        #region Public Methods and Operators        /// <summary>        /// The create pages.        /// </summary>        public override void CreatePages()        {            this.Pages.Add(new IntroductionPage());            this.Pages.Add(new ResultsPage());            this.Pages.Add(new ConclusionPage());            this.Pages.Add(new SummaryPage());            this.Pages.Add(new BibliographyPage());        }        #endregion    }}// Output:/*Resume -------SkillsPageEducationPageExperiencePageReport -------IntroductionPageResultsPageConclusionPageSummaryPageBibliographyPage*/
           

給我老師的人工智慧教程打call!http://blog.csdn.net/jiangjunshow

這裡寫圖片描述