Sunday 19 December 2010

Facade Pattern

"Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use."


The dictionary defines a façade as:
  1. The face of a building, especially the principal face.
  2. An artificial or deceptive front.
The second definition is exactly what the façade is – it makes using the subsystem much easier. In the code example below getting Jessie's bag ready before embarking on a weekend away has an onerous and chatty interface. The facade simplifies the interface by providing a single method to encapuslate all the lower level calls.

using System;
using System.Collections.Generic;

namespace Facade
{
    class Program
    {
        static void Main(string[] args)
        {
            JessiesBag bag =
                JessieFacade.GetJessiesBagReady(
                Vehicle.VehicleType.Car, 3, JessiesLead.LeadType.Long);
        }
    }
 
    public class JessieFacade
    {
        public static JessiesBag GetJessiesBagReady(
            Vehicle.VehicleType preferredVehicle,
            int days,
            JessiesLead.LeadType preferredLead)
        {
            JessiesBag bag = new JessiesBag();           
 
            Vehicle transport = new Vehicle();
            transport.SelectedVehicle = preferredVehicle;
 
            JessiesFood food = new JessiesFood();
            int scoops = JessiesFood.CalculateScoops(days);
            food.Pack(scoops, bag);
 
            JessiesBowls bowl = new JessiesBowls();
            if (bowl.NeedToPack(transport.SelectedVehicle))
            {
                bowl.Pack(bag);
            }
 
            JessiesLead lead = new JessiesLead();
            lead.Pack(preferredLead, bag);
 
            return bag;
        }
    }
 
    public class JessiesBag : List<object>
    {      
    }
 
 
    public class Vehicle
    {
        public enum VehicleType
        {
            Car,
            Van
        };
 
        public VehicleType SelectedVehicle { getset; }                    
    }
 
    public class JessiesFood
    {
        private List<int> _foodTin = new List<int>();
 
        public static int CalculateScoops(int days)
        {
            return 4 * days;
        }
 
        public void Pack(int scoops, JessiesBag bag)
        {
           _foodTin.Add(scoops);
           bag.Add(_foodTin);
        }
    }
 

No comments:

Post a Comment