Design Pattern in .NET 101 - Facade Pattern (Structural Pattern)
By admin on Jan 10, 2008 in .NET, Programming, Structural
Facade Pattern provides a unified interface to a set of interfaces in a subsystem. It defines a higher-level interface that makes the subsystem easier to use.
E.g.
I have a Call Details Record (CDR) to be processed by different systems. It is defined in the CDR class
using System;
using System.Collections.Generic;
using System.Text;
namespace FacadePattern
{
class CDR
{
private string aNo;
private string bNo;
private double chargedPrice;
private string imsi;
private string imei;
public CDR(string aNo, string bNo,
double chargedPrice,
string imsi, string imei)
{
this.aNo = aNo;
this.bNo = bNo;
this.chargedPrice = chargedPrice;
this.imsi = imsi;
this.imei = imei;
}
public string ANo
{
get
{
return this.aNo;
}
set
{
this.aNo = value;
}
}
public string BNo
{
get
{
return this.bNo;
}
set
{
this.bNo = value;
}
}
public double ChargedPrice
{
get
{
return this.chargedPrice;
}
set
{
this.chargedPrice = value;
}
}
public string IMSI
{
get
{
return this.imsi;
}
set
{
this.imsi = value;
}
}
public string IMEI
{
get
{
return this.imei;
}
set
{
this.imei = value;
}
}
}
}
The subsystems are RatingEngine and BillingSystem.
using System;
using System.Collections.Generic;
using System.Text;
namespace FacadePattern
{
class RatingEngine
{
public bool Rate(CDR cdr)
{
Console.WriteLine("Rate the CDR.");
return true;
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace FacadePattern
{
class BillingSystem
{
public bool Bill(CDR cdr)
{
Console.WriteLine("Bill the CDR.");
return true;
}
}
}
CDRProcessor calls the subsystems to process the CDR.
using System;
using System.Collections.Generic;
using System.Text;
namespace FacadePattern
{
class CDRProcessor
{
private RatingEngine ratingEngine;
private BillingSystem billingSystem;
public CDRProcessor()
{
ratingEngine = new RatingEngine();
billingSystem = new BillingSystem();
}
public bool Process(CDR cdr)
{
Console.WriteLine("Process the CDR.");
return (ratingEngine.Rate(cdr) &&
billingSystem.Bill(cdr));
}
}
}
To test it,
using System;
using System.Collections.Generic;
using System.Text;
namespace FacadePattern
{
class Program
{
static void Main(string[] args)
{
CDR cdr = new CDR("123", "456",
1.5, "12121212121", "1223232323");
CDRProcessor cdrProcessor = new CDRProcessor();
bool isProcessed = cdrProcessor.Process(cdr);
Console.Read();
}
}
}
The output
Process the CDR. Rate the CDR. Bill the CDR.
