Query on Facade Pattern

1 view
Skip to first unread message

govind

unread,
Sep 25, 2005, 8:15:19 AM9/25/05
to C# Design Patterns
Hi

I am using the Facade Pattern to create a web application.

I've got 3 sets of classes:

Database classes to fetch data from the database

Action Classes to display data on the web interface

Facade class which uses objects of the database classes and gives a set
of functions to the Action Classes.

Should I create the objects of the Database classes directly in the
Facade class or should I use an interface for the Database classes in
the Facade class?
I want to do this so that if I want to use any object of the Database
class directly in the Action Class(through the Facade Class that is...)
then I dont have to access the Database Class Objects directly in the
Action Class.

Jupiter Moon

unread,
Oct 12, 2005, 5:29:15 AM10/12/05
to C# Design Patterns
Hi Govind,

You need to have a look at Constructor Dependancy Injection and
Inversion of Control (IoC) - a quick Google search will give you all
you need (picocontainer.org has some good examples).

Basically your object should not take responsibility for creating the
database objects - they should be passed to it in it's constructor.
So:
BAD:
public class Façade
{
DatabaseObject myDatabaseObject;
public Façade ()
{
myDatabaseObject = new DatabaseObject();
}
}
GOOD:
public class Façade
{
private readonly IDatabaseObject myDatabaseObject;
public Façade (IDatabaseObject injectedDatabaseObject)
{
myDatabaseObjects = injectedDatabaseObject;
}
}

Then you create the Façade with:
DatabaseObject injectDatabaseObject = new ADODatabaseObject();
Façade façade = new Façade(injectDatabaseObject);
And if you change you're implementation you do:
DatabaseObject injectDatabaseObject = new MySqlDatabaseObject();
Façade façade = new Façade(injectDatabaseObject);

The important things to note are that CDI requires an interface not a
specific object (this allows for polymorphism and eases testing with
NMock etc.). Also note how the field is readonly - this protects the
DatabaseObject from being 'stained' by the façade (of course you
can still make calls on it etc.).

If you wish you can use something like PicoContainer (there is a .NET
version if you wish to compile yourself) or Spring.NET. These give IoC
which give the container control of the creation/disposal of the
objects. Spring.NET and NanoContainer (an extension to pico) allow you
to use a XML config file to determine which objects to inject. This
makes your implementation highly flexible - e.g. you could have two
deployments - one with MSSQL another with Oracle and all you change
is the config file.

Hope this helps.

govind

unread,
Nov 1, 2005, 5:36:50 AM11/1/05
to C# Design Patterns
Thanks Jupiter Moon!

Reply all
Reply to author
Forward
0 new messages