Factory Method Patterns : Factory Pattern « Design Patterns « C# / CSharp Tutorial






using System;
using System.Collections;
  public abstract class Section
  {
    public abstract void SomeSection();
  }
  public class TitleSection: Section
  {
    
    public override void SomeSection()
    {
      Console.WriteLine("title.");
    }  
        
    public TitleSection(){;}
    
  }
  public class HeaderSection: Section
  {
    public override void SomeSection()
    {
      Console.WriteLine("header.");
    }
    public HeaderSection(){;}
  }
  public class FooterSection: Section
  {
        public override void SomeSection()
        {
            Console.WriteLine("footer.");
        }
    public FooterSection(){;}

  }
  public class MenuSection: Section
  {
    public override void SomeSection()
    {
      Console.WriteLine("menu.");
        }
            
    public MenuSection(){;}
  }
  public class CatalogPage: Page
  {
    public override void AddSection(){
      this.pageCompositor.Clear();
      this.pageCompositor.Add(new TitleSection());
      this.pageCompositor.Add(new FooterSection());
    }
    public override void DisplayPage(){
      Console.WriteLine("Catalog page contains:");
      foreach(Section c in this.pageCompositor)
        c.SomeSection();
    }
    public CatalogPage()
    {
      this.AddSection();
    }
  }
  public class ManualPage: Page
  {
    public override void AddSection()
    {
      this.pageCompositor.Clear();
      this.pageCompositor.Add(new MenuSection());
      this.pageCompositor.Add(new FooterSection());
      this.pageCompositor.Add(new HeaderSection());

    }
    public override void DisplayPage()
    {
      Console.WriteLine("Manual page contains:");
        foreach(Section c in this.pageCompositor)
        c.SomeSection();
      Console.WriteLine();
    }
    public ManualPage(){;}
  }
  public abstract class Page
  {
    protected ArrayList pageCompositor = new ArrayList();
    public abstract void AddSection();
    public abstract void DisplayPage();
  }  
  class Client
  {
    static void Main(string[] args)
    {
      Page p = new  CatalogPage();
      p.AddSection();
      p.DisplayPage();
  
      p = new ManualPage();
      p.AddSection();
      p.DisplayPage();
      
    }
  }








28.2.Factory Pattern
28.2.1.Use a static class factory
28.2.2.Factory Method Patterns
28.2.3.Abstract Factory