In the previous post I was at a point where the baby was feeding, sleeping and most importantly making sure we spend money on nappies. In this post I attempt to extend my initial design.
So far my TheSpecialOne class looked like below:
A week went pass and after many hours of sleepless nights we realised that the baby was constantly hungry. Being responsible parents we kept on breast feeding, but it was time for the magic formula milk.
Our requirements were very simple. We wanted to be able to breast feed and swap to formula milk to top up. We wanted make this change without having to disturb the baby too much (or without him knowing).
If you take a step back, we see that feeding is an activity and only the method used for feeding is what is changing. So in reality we should be able to swap between different implementations (of feeding methods) without changing the abstraction. We would need the flexibility to alter the feeding process independent of the method used. Sounds familiar? What I am describing here is the Bridge pattern.
I have done some fundamental changes to my initial design. I introduced a new interface called IFeedStyle. This is the abstraction I will use to introduce different methods of feeding (e.g. bottle, spoon feed etc).
However I know that as he grows, we will need to be flexible. Consider the following code.
The key aspect here is that the "Start()" method is abstract. This way I can create as many derived classed as I want. As the baby grows his eating habits will change. While he is a baby, he may only take milk, but when he becomes a toddler some solid food. But while having solid food he may like to play with some toys but drink milk using a bottle. The idea is simple, based on different strategies, we can decide how to feed. For the moment we will only have a baby specific implementation of this abstract class.
The above abstract class must be integrated to the Person class. The following is the modified Person class.
I think you should see the advantage of using the Bridge pattern. The actual task of feeding does not change, only the implementation that meets the FeedableBase class. We can provide different implementation without modifying the Person class. Now the IFeedingStyle and FeedableBase can change independently.
All set, the calling code looks like this:
More to the point, the output looks like this.
Enough fun and back to real work!! (code is here)
Labels
Android
Android part 1
Architecture
Article
ASP.NET
ASP.NET MVC
Async
AWS
AWS CLI
Baby
base image
Basic Concepts
Bridge pattern
C#
CallContext
Castle Windsor
CloudFormation
Command line
Continuous Integration
Coursera
Create IAM policy
Custom AMI
DaiySelfie
Design patterns
EC2
Encapsulation
Entity Framework
Geolocation
Google App Engine
HTML
HTML5
IAM
IIS
Improvements
Inheritance issues
Instance user data
Ioc
Java
JavaScript
KnockoutJs
Lanching EC2
Learning
Memory
MSBuild
OOP
pair programming
Perfmon
Pluralsight
Principals
Python
SimpleAPI
Sockets
Solutions Architect
SQL Server
SQS
State pattern
TFS 2010
Threading
Type Covariance
Udacity
Unit testing
Visitor pattern
WCF
Web Development
WebApi
Windows VMs
Showing posts with label Design patterns. Show all posts
Showing posts with label Design patterns. Show all posts
Saturday, 29 June 2013
Sunday, 16 June 2013
The God object (discovery) [1]
In Software Engineering the God object this refers to an object that every other object depends on. I am sure simple search on the internet will yield dozens of articles describing the pros-n-cons of using a God object.
My son is very special to me, therefore I did not hesitate to make a brand new instance of this Person. We cannot create an instance of a Abstract class, however we can derive from it. I called this specialisation TheSpecialOne.
You might wonder why I decided Abstract the "Cry()" method as above. The reason is quite simple. Each baby cries differently. Some can be very loud but others are not. Therefore I decided my son can decide how best to cry :-).
Me and my wife welcomed our son few weeks ago and I was immensely busy. It is only today that I managed to find few hours to myself to write this note. When it comes to baby stuff, I think whatever the literature that is available in the market is only half the story (or may be less). Having a child changes everything. This ever-hungry machine will forever change your life and mostly in a good way. Yes, you will loose few hours of sleep here and there but I think its absolutely worth it. The joy and happiness that this new member brings to your small family is priceless. Enough talk.... :-)
The God object is like a baby. We know its there, but for an application point of view its a big black box. The God object can do everything, (e,g write to database, file system, resolve dependencies etc). For a development team that is mature, understanding what the God object is not that difficult. However for a new member its similar to becoming a father/mother for the first time. You just know its there, but just do not know how to use it!
So what do I know about the Baby (God) object. The only thing that I knew at the beginning was it derived from a very generic class Person. Thanks to to modern wonders of science and technology we found out the gender of the baby. Therefore we knew its a Person and had a property called Gender which was set to to Male. So my abstract world looked like this.
After the baby was born I soon realise that this God object has a very simple and effective behavior. Crying. I have to say is very effective and the best way to model this behavior was to implement ICanCry interface. Crying can sometimes be a Big thing! especially for a new born. My object model was evolving.
My son is very special to me, therefore I did not hesitate to make a brand new instance of this Person. We cannot create an instance of a Abstract class, however we can derive from it. I called this specialisation TheSpecialOne.
You might wonder why I decided Abstract the "Cry()" method as above. The reason is quite simple. Each baby cries differently. Some can be very loud but others are not. Therefore I decided my son can decide how best to cry :-).
This does not look right, don't you agree? Well, every person should have a gender. We need to ensure that this is a required property. The best way to make sure that the Gender is populated is to have the Person class to contain a constructor that takes in the gender as a parameter.
We were starting to forget the most important piece of the puzzle. The Name. There is no doubt that a person should have a name, therefore I introduced the new Name property to the Person class.
We were starting to forget the most important piece of the puzzle. The Name. There is no doubt that a person should have a name, therefore I introduced the new Name property to the Person class.
Few hours after the baby was born he was ready to feed. As this is a fundamental behavior of a person, I thought of introducing this behavior to the Person class for the moment.
It did not take even few more hours to realise another fundamental behaviors. These were "poo" and "sleep". So I modeled this in to my glorified Person class.
One thing I did do was to implement "Poo" in the base class itself. Whatever we take has to come out at some point. Therefore I did not really see the point of having a specialisation of "Poo" in my TheSpecialOne class.
So far my son is feeding, sleeping, crying and can poo. (Code is here.)
Labels:
Baby,
C#,
Design patterns
Monday, 11 February 2013
"Simple" Service Locator
The Service Locator pattern has been subjected to many arguments and surely it will continue for many more years. As usual the best source to learn about the Service Locator pattern is from Martin Fowler.
Design patterns, when used correctly can help to "craft" the software. However design patterns can easily make the code hard to understand too. So I guess there should always be a balance. My objective of this post is not to argue that Service Locator is an anti-pattern or not. My goal is just to write few lines of code and see how all fits together. I thought I will write a "form" of service locator that anyone can understand.
The interface of the "simple" Service Locator looks like below:
I created a simple Console application that uses this Service Locator. The usage looks like below:
A type implementing multiple interfaces must be registered separately.
Only an interface can be registered against a type. ... etc etc, Many more.
If you interested in the code you can download it from GitHub.
Design patterns
Design patterns, when used correctly can help to "craft" the software. However design patterns can easily make the code hard to understand too. So I guess there should always be a balance. My objective of this post is not to argue that Service Locator is an anti-pattern or not. My goal is just to write few lines of code and see how all fits together. I thought I will write a "form" of service locator that anyone can understand.
"Simple" Service Locator
The interface of the "simple" Service Locator looks like below:
I created a simple Console application that uses this Service Locator. The usage looks like below:
Limitations
A type must always implement an Interface.A type implementing multiple interfaces must be registered separately.
Only an interface can be registered against a type. ... etc etc, Many more.
If you interested in the code you can download it from GitHub.
Labels:
C#,
Design patterns
Wednesday, 18 July 2012
Back to basics (IDisposable)
In simple terms Disposable pattern provides a method to de-allocate resource in a deterministic fashion.
The .NET Framework provides the "IDisposable" interface which we should use to implement the disposable pattern. The interface is very simple (see below).
public interface IDisposable
{
void Dispose();
}
The "expensive" resources are considered to be calls to files, databases, streams. We should consider implementing IDisposable pattern and gracefully release resources where necessary. So, how do we go about implementing the IDisposable pattern. Consider the following code snippet.
internal class ExpensiveResource : IDisposable
{
private bool _disposed = false;
public void DoExpensiveWork()
{
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
ReleaseExpensiveResources();
_disposed = true;
}
}
private void ReleaseExpensiveResources()
{
}
}
To start, we have implemented the "IDisposable" interface for the type "ExpensiveResource". We have a overloaded "Dispose" method. We use the overloaded method to add our custom code (i.e. code to release resources).
Most importantly, the "Dispose" method can be called multiple times.Therefore we need to add safe guards in place. This is where "_disposed" field comes into play.
Since we are taking the ownership of disposing the object, there is no need for the Garbage Collector (GC) to call the "Finalize" method to dispose the object. Therefore we can suppress the call to Finalize. This is carried out by calling the "GC.SuppressFinalize(this))".
The C# "using" keyword can be used to elegantly dispose a disposable object. The consumer can write the following.
internal class MyTestClass
{
public void DoStuff()
{
using (var expensiveWork = new ExpensiveResource())
{
//
Do work
} - (1)
}
}
By the time the execution reach (1) the dispose defined in the type is called and object is disposed.
.NET Tasks and IDisposable
.NET Framework "Task" by design implements the "IDisposable" interface, therefore an disposable object. But if we have to keep calling dispose at the end of each Task, then the source code will most surely become unreadable.
Read the following post from Stephen Toub - MSFT for more on disposing Tasks.
[The recommendation is not to dispose a Task unless you explicitly cause a Task to allocate a IAsyncResult.AsyncWaitHandle.]
Labels:
C#,
Design patterns
Monday, 18 June 2012
Good design by Dieter Rams...
We all need good designs that meet expectations.
Following are some key design principals by Dieter Rams, which basically applies to every design.
"
- Is innovative - The possibilities for innovation are not, by any means, exhausted. Technological development is always offering new opportunities for innovative design. But innovative design always develops in tandem with innovative technology, and can never be an end in itself.
- Makes a product useful - A product is bought to be used. It has to satisfy certain criteria, not only functional, but also psychological and aesthetic. Good design emphasizes the usefulness of a product whilst disregarding anything that could possibly detract from it.
- Is aesthetic - The aesthetic quality of a product is integral to its usefulness because products are used every day and have an effect on people and their well-being. Only well-executed objects can be beautiful.
- Makes a product understandable - It clarifies the product’s structure. Better still, it can make the product clearly express its function by making use of the user's intuition. At best, it is self-explanatory.
- Is unobtrusive - Products fulfilling a purpose are like tools. They are neither decorative objects nor works of art. Their design should therefore be both neutral and restrained, to leave room for the user's self-expression.
- Is honest - It does not make a product more innovative, powerful or valuable than it really is. It does not attempt to manipulate the consumer with promises that cannot be kept.
- Is long-lasting - It avoids being fashionable and therefore never appears antiquated. Unlike fashionable design, it lasts many years – even in today's throwaway society.
- Is thorough down to the last detail - Nothing must be arbitrary or left to chance. Care and accuracy in the design process show respect towards the consumer.
- Is environmentally friendly - Design makes an important contribution to the preservation of the environment. It conserves resources and minimizes physical and visual pollution throughout the lifecycle of the product.
- Is as little design as possible - Less, but better – because it concentrates on the essential aspects, and the products are not burdened with non-essentials. Back to purity, back to simplicity.
"
Source Wikipedia.
Labels:
Design patterns
Tuesday, 22 May 2012
Visiting the visitor pattern
A colleague of mine showed me the following result.
----------------------------------------------------------------
Current Drawing
----------------------------------------------------------------
Rectangle (10,10) width=30 height=40
Square (15,30) size=35
Ellipse (100,150) diameterH = 300 diameterV = 200
Circle (1,1) size=300
Textbox (5,5) width=200 height=100 Text="sample text"
He asked me whether I can write a simple console application to achieve the above result. Simple task you might say.
Well.. it is pretty obvious that we need to start off with an abstract "Shape" class. But what about the logic to "draw" the shape on the canvas. What we need is an interface like "ICanDraw", which contains the "draw" method. Now, the Shapes can be drawn, therefore the Shape should implement the "ICanDraw" interface. But hang on, each Shape should present itself to the canvas. The canvas should then decide how to "draw" the shape on the canvas.
The most interesting piece here is the text box. A text box is not strictly a shape, but a "Rectangle" with a additional text property. We can say that a text box is composed of a Rectangle. Internally the text box will use the Rectangle to represent itself.
See the following UML.
My "ICanDraw" interface looks like below.
The abstract "Shape" class looks like below.
Keep a close eye on the abstract "Draw" method. Also notice that the "X" and "Y" are "readonly" properties. This plays nicely to the immutability of objects
The "Circle" class looks like below:
The code for the text box looks like below.
Ok, we have all the concrete classes and a special text box.
Next piece of the puzzle is the "ICanvas". Since we are just writing the content to the console, this will be a special console canvas. The canvas is aware of the shapes and will decide how to draw them. The responsibility to draw a shape is now with the canvas.
The following is the special implementation of "ICanvas" for the console.
As you can see the canvas is aware of the shapes and it decides how to draw them. The canvas will determine this by the runtime type of the object.
Can you see a pattern here? This is in fact the "Visitor" pattern. The purpose of the visitor pattern is to choose a functionality depending on the run-time type of an object. The pattern is also used to introduce additional functionality to an object.
So how do we "draw" these shapes. See below.
The special "ConsoleCanvas" visits each shape and "draws" it on the console.
In terms of SOLID principals, the "Shape" class is open for extensions and closed for modifications . Yes, the Open/Close principal.
But can the same functionality be achieved through another pattern?
----------------------------------------------------------------
Current Drawing
----------------------------------------------------------------
Rectangle (10,10) width=30 height=40
Square (15,30) size=35
Ellipse (100,150) diameterH = 300 diameterV = 200
Circle (1,1) size=300
Textbox (5,5) width=200 height=100 Text="sample text"
He asked me whether I can write a simple console application to achieve the above result. Simple task you might say.
Well.. it is pretty obvious that we need to start off with an abstract "Shape" class. But what about the logic to "draw" the shape on the canvas. What we need is an interface like "ICanDraw", which contains the "draw" method. Now, the Shapes can be drawn, therefore the Shape should implement the "ICanDraw" interface. But hang on, each Shape should present itself to the canvas. The canvas should then decide how to "draw" the shape on the canvas.
The most interesting piece here is the text box. A text box is not strictly a shape, but a "Rectangle" with a additional text property. We can say that a text box is composed of a Rectangle. Internally the text box will use the Rectangle to represent itself.
See the following UML.
My "ICanDraw" interface looks like below.
/// <summary> /// This interface indicates that the shape can be drawn. /// </summary> public interface ICanDraw { void Draw(ICanvas canvas); }
The abstract "Shape" class looks like below.
/// <summary> /// This is the base class for a shape. /// </summary> public abstract class Shape : ICanDraw { public int X { get; private set; } public int Y { get; private set; } protected Shape(int x, int y) { X = x; Y = y; } public abstract void Draw(ICanvas canvas); }
Keep a close eye on the abstract "Draw" method. Also notice that the "X" and "Y" are "readonly" properties. This plays nicely to the immutability of objects
The "Circle" class looks like below:
/// <summary> /// This is the concrete implementation of a circle. /// </summary> public class Circle : Shape { public int Size { get; private set; } public Circle(int x, int y, int size) : base(x, y) { Size = size; } public override void Draw(ICanvas canvas) { canvas.Draw(this); } }
The code for the text box looks like below.
/// <summary> /// This is the concrete implementation of a text box. /// </summary> public class Textbox : ICanDraw { public Rectangle Rectangle { get; private set; }public string Content { get; private set; } public Textbox(int x, int y, int width, int height, string content) { Rectangle = new Rectangle(x, y, width, height); Content = content; } public void Draw(ICanvas canvas) { canvas.Draw(this); }}
Ok, we have all the concrete classes and a special text box.
Next piece of the puzzle is the "ICanvas". Since we are just writing the content to the console, this will be a special console canvas. The canvas is aware of the shapes and will decide how to draw them. The responsibility to draw a shape is now with the canvas.
The following is the special implementation of "ICanvas" for the console.
/// <summary> /// This is the "canvas" representing the console. /// </summary> public class ConsoleCanvas : ICanvas { public void Draw(Circle item) { Console.WriteLine("Circle({0},{1}) Size={2}", item.X, item.Y, item.Size); } public void Draw(Rectangle item) { Console.WriteLine("Rectangle({0},{1}) Width={2}, Height={3}", item.X, item.Y, item.Width, item.Height); } public void Draw(Square item) { Console.WriteLine("Square({0},{1}) Size={2}", item.X, item.Y, item.Size); } public void Draw(Ellipse item) { Console.WriteLine("Ellipse({0},{1}) DiameterH={2}, Diameter={3}", item.X, item.Y, item.DiameterH, item.DiameterV); } public void Draw(Textbox item) { Console.WriteLine("TextBox({0},{1}) Width={2}, Height={3}, Text={4}", item.Rectangle.X, item.Rectangle.Y, item.Rectangle.Width, item.Rectangle.Height, item.Content); } }
As you can see the canvas is aware of the shapes and it decides how to draw them. The canvas will determine this by the runtime type of the object.
Can you see a pattern here? This is in fact the "Visitor" pattern. The purpose of the visitor pattern is to choose a functionality depending on the run-time type of an object. The pattern is also used to introduce additional functionality to an object.
So how do we "draw" these shapes. See below.
private static void Load()
{
var items = new List<ICanDraw>()
{
new Rectangle(10, 10, 30, 40),
new Square(15, 30, 35),
new Ellipse(100, 150, 300, 200),
new Circle(1, 1, 300),
new Textbox(5, 5, 200, 100, "Sample Text")
};
items.ForEach(item => item.Draw(new ConsoleCanvas()));
}
The special "ConsoleCanvas" visits each shape and "draws" it on the console.
In terms of SOLID principals, the "Shape" class is open for extensions and closed for modifications . Yes, the Open/Close principal.
But can the same functionality be achieved through another pattern?
Labels:
C#,
Design patterns,
Visitor pattern
Saturday, 5 May 2012
State and Strategy patterns
The State and Strategy patterns are very similar to each other but their use is somewhat different.
The state pattern is a way of encapsulating the behaviour of each state an object goes through. The state pattern fits nicely to model the operation of an ATM machine.
The key difference is that the state pattern is used to identify "states" which an object goes through. Where as the strategy pattern encapsulates a behaviour of the object. The state classes can be aware of the other states. This raise the question of coupling. For a system that is dynamically changing, then having states "knowing" other states might be acceptable.
The strategy on the other hand is an isolated functional unit and there is no interaction between the strategies. The context can choose which strategy to use where as the state is changed by changes to the internal state of the object. The most obvious way to use the strategy pattern is with the factory method.
The state pattern is a way of encapsulating the behaviour of each state an object goes through. The state pattern fits nicely to model the operation of an ATM machine.
The key difference is that the state pattern is used to identify "states" which an object goes through. Where as the strategy pattern encapsulates a behaviour of the object. The state classes can be aware of the other states. This raise the question of coupling. For a system that is dynamically changing, then having states "knowing" other states might be acceptable.
The strategy on the other hand is an isolated functional unit and there is no interaction between the strategies. The context can choose which strategy to use where as the state is changed by changes to the internal state of the object. The most obvious way to use the strategy pattern is with the factory method.
Labels:
C#,
Design patterns,
State pattern
Sunday, 15 April 2012
Visitor Pattern : Revisited
Some developers find design patterns an "Advance" topic. But the reality is that we use design pattern every day and mostly without even knowing.
I find design patterns as an essential element in everyday development. I agree that reading the "Design Patterns" by the Gang of Four (GOF) can be challenging. But trust me, its worth the effort. Although I have not read this book cover to cover, it is an essential reference that you should have access to.
The intent of Visitor pattern according to GOF is "Represent an operation to be performed on elements of an object structure. Visitor lets you to define a new operation without changing the classes of the elements on which it operates.". I think for a developer, the second sentence is the most important piece "without changing the classes".
Consider an example where two tax rate applied to people based on their earnings. The idea here is to create a "Visitor" to calculate the tax.
[Lets have a quick look at the UML. - Created using Creately]
Lets start with the "Person" class. This is an abstract class.
The above immutable class has a method called "Accept". This is where we "inject" the visitor. The "Person" class is ready to entertain a "Visitor".
The next step is to create the two types of people. In this example they are high and low earners.
This is followed by the low earning person.
Both classes looks similar, but take a closer look at the "Accept" method. The "Accept" method receives the "Visitor" and calls the "Visit" method passing in the current object. The "Visitor" is now aware of the type of person it is dealing with.
The following is the interface of the "IVisitor".
The "IVisitor" works with the concrete "Person" types. So in this case "HighEarningPerson" and "LowEarningPerson". You can see that "IVisitor" is using the method overloading.
Lets look at the implementation of the "IVisitor".
Do not pay too much attention to the "ITaxCalculatorFactory" that is used here. The reason for using the "ITaxCalculatorFactory" is to keep the creation of the objects out from business processes. Always keep in a note of the Inversion of Control (IoC).
The "TaxVisitor" calculates the tax rate of each person and displays the result.
Lets see how all of this fits in..
I have created a "Console" application. See the following class.
We have a collection of "Person" objects. Each has its own type (Low and High earnings). The "TaxVisitor" visits each object and calculates the tax. The output looks like below.
We can clearly see that correct calculate method in the "TaxVisitor" is been called based on the type of the object.
The Visitor pattern is uses the "double-dispatch" to resolve a method call. Double-dispatch simply means the ability to choose the correct method at run-time. So in the above case, although we iterate over a collection of "Person" objects, the run-time type has been used to pick the correct method in the visitor.
Hope you will find this note useful.
I find design patterns as an essential element in everyday development. I agree that reading the "Design Patterns" by the Gang of Four (GOF) can be challenging. But trust me, its worth the effort. Although I have not read this book cover to cover, it is an essential reference that you should have access to.
The intent of Visitor pattern according to GOF is "Represent an operation to be performed on elements of an object structure. Visitor lets you to define a new operation without changing the classes of the elements on which it operates.". I think for a developer, the second sentence is the most important piece "without changing the classes".
Consider an example where two tax rate applied to people based on their earnings. The idea here is to create a "Visitor" to calculate the tax.
[Lets have a quick look at the UML. - Created using Creately]
Lets start with the "Person" class. This is an abstract class.
/// <summary> /// This is the base class for people. /// </summary> public abstract class Person { public string Name { get; private set; } protected Person(string name) { Name = name; } /// <summary> /// Accept a visitor so that new functionality can be added to the <see cref="Person"/>. /// </summary> public abstract void Accept(IVisitor visitor); }
The above immutable class has a method called "Accept". This is where we "inject" the visitor. The "Person" class is ready to entertain a "Visitor".
The next step is to create the two types of people. In this example they are high and low earners.
/// <summary> /// This is a concrete class of a <see cref="Person"/>. /// </summary> public class HighEarningPerson : Person { public decimal Salary { get; private set; } public decimal Rate { get; private set; } public HighEarningPerson(string name, decimal salary, decimal rate) : base(name) { Salary = salary; Rate = rate; } /// <summary> /// The Visitor to this object works on the <see cref="HighEarningPerson"/> instance. /// </summary> public override void Accept(IVisitor visitor) { visitor.Visit(this); } }
This is followed by the low earning person.
/// <summary> /// This is a concrete class of a <see cref="Person"/>. /// </summary> public class LowEarningPerson : Person { public decimal Salary { get; private set; } public decimal Rate { get; private set; } public LowEarningPerson(string name, decimal salary, decimal rate) : base(name) { Salary = salary; Rate = rate; } /// <summary> /// The Visitor works on the instance of <see cref="LowEarningPerson"/>. /// </summary> /// <param name="visitor"></param> public override void Accept(IVisitor visitor) { visitor.Visit(this); } }
Both classes looks similar, but take a closer look at the "Accept" method. The "Accept" method receives the "Visitor" and calls the "Visit" method passing in the current object. The "Visitor" is now aware of the type of person it is dealing with.
The following is the interface of the "IVisitor".
/// <summary> /// This is the interface of the Visitor that /// works on the concrete types of people. /// </summary> public interface IVisitor { void Visit(HighEarningPerson highEarningPerson); void Visit(LowEarningPerson lowEarningPerson); }
The "IVisitor" works with the concrete "Person" types. So in this case "HighEarningPerson" and "LowEarningPerson". You can see that "IVisitor" is using the method overloading.
Lets look at the implementation of the "IVisitor".
/// <summary> /// This is the Visitor that calculates the tax for each person. /// </summary> public class TaxVisitor : IVisitor { private readonly ITaxCalculatorFactory _taxCalculatorFactory; public TaxVisitor(ITaxCalculatorFactory taxCalculatorFactory) { _taxCalculatorFactory = taxCalculatorFactory; } public void Visit(HighEarningPerson highEarningPerson) { var taxCalculator = _taxCalculatorFactory.Create(TaxType.High); var tax = taxCalculator.Calculate(highEarningPerson.Salary, highEarningPerson.Rate); Console.WriteLine("The tax for '{0} - HIGH' is £{1:00}", highEarningPerson.Name, tax); } public void Visit(LowEarningPerson lowEarningPerson) { var taxCalculator = _taxCalculatorFactory.Create(TaxType.Low); var tax = taxCalculator.Calculate(lowEarningPerson.Salary, lowEarningPerson.Rate); Console.WriteLine("The tax for '{0} - LOW' is £{1:00}", lowEarningPerson.Name, tax); } }
Do not pay too much attention to the "ITaxCalculatorFactory" that is used here. The reason for using the "ITaxCalculatorFactory" is to keep the creation of the objects out from business processes. Always keep in a note of the Inversion of Control (IoC).
The "TaxVisitor" calculates the tax rate of each person and displays the result.
Lets see how all of this fits in..
I have created a "Console" application. See the following class.
public class VisitorPattern : ITest { public void Execute() { Console.WriteLine("**** VISITOR Pattern *****"); var lowTaxRate = 0.023M; var highTaxRate = 0.04M; var people = new List<Person>() { new LowEarningPerson("Bob", 23000, lowTaxRate), new HighEarningPerson("Alice", 45000, highTaxRate), new LowEarningPerson("Peter", 13000, lowTaxRate), new HighEarningPerson("Pan", 100000, highTaxRate) }; var taxCalculatorFactory = new TaxCalculatorFactory(); var taxVisitor = new TaxVisitor(taxCalculatorFactory); people.ForEach(person => person.Accept(taxVisitor)); } }
We have a collection of "Person" objects. Each has its own type (Low and High earnings). The "TaxVisitor" visits each object and calculates the tax. The output looks like below.
We can clearly see that correct calculate method in the "TaxVisitor" is been called based on the type of the object.
The Visitor pattern is uses the "double-dispatch" to resolve a method call. Double-dispatch simply means the ability to choose the correct method at run-time. So in the above case, although we iterate over a collection of "Person" objects, the run-time type has been used to pick the correct method in the visitor.
Hope you will find this note useful.
Labels:
C#,
Design patterns,
Visitor pattern
Subscribe to:
Posts (Atom)



