Adapter Pattern
Continuing the tour in the structural patterns I'm going to introduce the adapter pattern.
You can read my previous posts on structural patterns here:
Decorator pattern
Proxy pattern
Facade pattern
The Adapter Pattern
The adapter pattern helps us to convert an interface of a class into another
interface that we need. It helps us to adapt old systems to new systems
without the need to rewrite the old systems. Also, adapter pattern enables
classes to work together even though they have an incompatible interfaces.
For a UML diagram of the pattern go to dofactory site.
How does it Work?
One way to implement the adapter pattern includes 3 participants -
an interface, an adaptee and an adapter. The interface defines the
operations we need in the adapter. The adaptee has it's original operations.
The adapter class inherits the adaptee class and implements the interface
by using the adaptee operations.
Another way to implement the adapter also includes 3 participants -
the class with operations to inherit (which replace the interface), an adaptee and an adapter.
In this case The class defines virtual methods, the adapter class inherit the
class and holds the adaptee as member. The adapter class overrides the class' virtual
methods and use the adaptee operations inside them.
Example in C#
Lets look at a simple example of the first way:
#region Interface
public interface IOperation
{
#region Methods
void Fly();
#endregion
}
#endregion
#region Adaptee
public class Car
{
#region Methods
public void Drive()
{
// do the operation of drive
}
#endregion
}
#endregion
#region Adapter
public class FlyingCar : Car, IOperation
{
#region IOperation Members
public void Fly()
{
// calling the drive method of the Car
this.Drive();
}
#endregion
}
#endregion
Summary
The adapter pattern is useful for places where you have a class with an operation
that you want to use but the interface of the class isn't compatible with the
interface that you need.
In the next post in this series I'll write about the composite pattern.
Enterprise Library - Building a Custom Trace Listener
Introduction
Early this week, I got a phone call from a customer.
The customer wanted to know how to build a new provider for logging application block in order to
log data to his log table and not to the suggested logging application block database.
Also, he wanted to know why to use the ent-lib at all.
I decided to write this post in order to show how to build such a provider and to answer why
I think you should use ent-lib.
Building a Custom Trace Listener
Building a new provider to the logging application block has some simple guidelines:
- Add using for the following namespaces:
using System.Diagnostics;
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
- Derive your class from CustomTraceListener class.
- Add the following attribute:
[ConfigurationElementType(typeof(CustomTraceListenerData))]
- Override TraceData method which is called by the TraceData of the LogSource class.
Also override the Write and WriteLine methods which write the specified message
to the listener.
That is all there is in the implementation.
Custom Trace Listener Example
using System.Diagnostics;
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
[ConfigurationElementType(typeof(CustomTraceListenerData))]
public class CustomTraceListenerExample : CustomTraceListener
{
#region Ctor
public CustomTraceListenerExample()
{
}
#endregion
#region
public override void Write(string message)
{
// implement the write action
}
public override void WriteLine(string message)
{
// implement the write line action
}
public override void TraceData(TraceEventCache eventCache, string source,
TraceEventType eventType, int id, object data)
{
if (data is LogEntry && Formatter != null)
{
// implement the action for the log entry data
}
else
{
// implement the action of the object you got probably you
// would use the Write method and write to the listener the object
// you got as string
}
}
#endregion
}
After you build the custom trace listener in order to use it in you application you should
do the following things:
Open the config file in the ent-lib designer.
Add a new custom trace listener.
Press the button of Type in the properties window.
Load the assembly that your custom trace listener is in it.
From now on you can use the new trace listener as you would have used other trace
listeners in ent-lib.
Why to Use Enterprise Library?
I gave a few lectures about ent-lib in the past and the question why to use ent-lib always raise.
To be honest I'm very subjective about this subject - I really love ent-lib.
But the following things I'm going to write are objective:
- The application blocks are proved technology with a large community behind them.
- The blocks were tested and are being tested by the patterns & practices team
and the bug rate declines.
- The blocks are integrate with one another and therefore have an advantage against
frameworks which were built to do only one thing like Log4Net for example.
- The blocks points to key features of application infrastructure - helps to develop
infra fast.
- Because the blocks are consistent, once you learn how to use a block it's
easy to learn how to use other blocks.
- Ent-lib has a designer tool for configurations that is integrated in visual studio.
The designer helps to configure the blocks and decrease the need to write
config files by ourselves.
- The application blocks simplify the code you write by providing a
convenient and readable code.
- The blocks are extensible - build your own providers or own block
(with the application block software factory).
There are more reasons to use ent-lib but these are the important ones.
Hope I helped you to decide to use ent-lib.
SketchPad - Entity Framework and LINQ to SQL Examples
Are you tired of Northwind examples?
Samir Bajaj a developer in the ADO.NET team has pubished a nice example of using the Entity Framework and LINQ to SQL.
The example is not the ordinary Northwind example but a win SketchPad application.
Samir implemented a startegy pattern that enable us to replace the data access between the two frameworks.
You can use either his Entity Framework implementation or his LINQ to SQL implementation.
I found this example very helpful.
Samir's post
Downlaod the example here
Facade Pattern
Continuing the tour in the structural patterns I'm going to present today the facade pattern.
You can read the my previous posts on structural patterns here: Decorator pattern | Proxy pattern.
What is the Facade Pattern?
The facade pattern is all about encapsulating a subsystem to make it easier to use.
To reduce complexity of systems we usually build them as a union of subsystems.
The facade hides the subsystem implementation and externalize an interface to that subsystem.
The facade interface can have a new set of operations or operations that included in the subsystem.
Another aspect of facade - the facade is an interface to a subsystem implementation and therefore you can remove
the subsystem and put another subsystem instead.
For a UML diagram of the pattern go to dofactory site.
A Facade Story
Recently, I used this pattern to mock a subsystem that is under construction.
In my current project I have two systems that I need to integrate.
The first system is a Blaze Advisor rules engine.
I use the Blaze to develop business rules.
The Blaze is part of the subsystem which also include classes to manipulate responses from the Blaze.
The second system is a mortgage system that sends requests to the Blaze through the facade and get responses from it as system data structures.
I didn't finished the implementations in the Blaze and I needed to test my application.
So what can you do?
I made a xml file with a "response" from the Blaze (I get responses from the Blaze through a web service) and loaded it to the Blaze proxy class.
Then I used the classes that manipulate the response as if I got the response form the Blaze and used the facade class to get the information I needed.
Example in C#
The facade pattern is simple to implement.
Make a namespace with internal classes.
Make a public class that hold those classes and have methods that use the internal classes and you have a facade.
Lets look at a self-explanatory example:
#region The Facade
public class PictureFacade
{
#region Members
private PictureLoader _pictureLoader;
private PictureShower _pictureShower;
#endregion
#region Ctor
public PictureFacade()
{
_pictureLoader = new PictureLoader();
_pictureShower = new PictureShower();
}
#endregion
#region Methods
/// <summary>
/// Constructing an operation of loading the picture first
/// and then showing it
/// </summary>
public void ShowPicture()
{
_pictureLoader.LoadPicture();
_pictureShower.ShowPicture();
}
#endregion
}
#endregion
#region The Subsystem
internal class PictureLoader
{
#region Methods
internal void LoadPicture()
{
Console.WriteLine("Loading a picture");
}
#endregion
}
internal class PictureShower
{
#region Methods
internal void ShowPicture()
{
Console.WriteLine("Showing a picture");
}
#endregion
}
#endregion
Summary
To sum up this post, the facade pattern is helpful to encapsulate a subsystem.
It helps us to look at a very complicated subsystem as a simple interface.
In the next post I'll write about the adapter pattern.
Early this week I talked to a friend.
One of the subjects in the conversation was the reading of professional books in order to gain knowledge.
I promised him my reading list for the next months and there it goes (by my order of reading):
- Expert C# 2005 Business Objects 2nd Edition.
- LINQ in Action.
- Programming WCF Services.
- ASP.NET 2.0 MVP Hacks and Tips.
- ASP.NET AJAX in Action.
- Practical Software Factories in .NET.
- Windows Workflow Foundation Step By Step.
- C# 3.0 Cookbook.
- C# 3.0 Design Patterns.
Also, I'm going to read again Martin Fowler's book - Patterns of Enterprise Application Architecture.
If you have books to recommend I'll be happy to get your comment.
I've been asked by friends and co-workers why I didn't written posts in the last weeks.
The main reason is that I'm learning for my next MCTS exam.
In the last 3 weeks I read and practiced the materials from the self-paced training kit for win forms.
While I was learning I found and read a Hebrew post by Justin Angel about certifications and I must agree with the things he wrote.
I want to explain one thing that he wrote:
I sometimes interview candidates that write in their resume that they passed MCP's or other certifications.
When that candidate can't tell me basic things (for example - what is session? how does it work?) I can tell that
the candidate used braindumps to pass the certification.
I don't disqualify that candidate because of that but it gives a bad impression about that candidate.
The certifications are meant to tell you that you reached a high level of understanding and knowledge.
When you use brainumps you don't learn and only cheat yourself.
I'll continue the posts about design patterns in the near future.