Topic: designpatterns
Domain Logic Patterns
Transaction Script
Organizes business logic by procedures where each procedure handles a single request from the
presentation.
Domain Model
An object model of the domain that incorporates both behavior and data
Table Module
A single instance that handles the business logic for all rows in a database table or view.
Service Layer
Defines an application's boundary with a layer of services that establishes a set of available
operations and coordinates the applications response in each operation.
Data Source Architectural Patterns
Table Data Gateway
An object that acts as a gateway to a database table. One instance handles all the rows in the
table.
Row Data Gateway
An object that acts as a gateway to a single record in a data source. There is one instance per row.
Active Record
An object that wraps a row in a database table or view, encapsulates the database access, and adds
domain logic on that data.
Data Mapper
A layer of mappers that moves data between objects and a database while keeping them independent of
each other and the mapper itself.
Object-Relational Behavioral Patterns
Unit of Work
Maintains a list of objects affected by a business transaction and coordinates the writing out of
changes and the resolution of concurrency problems.
Identity Map
Ensures that each object gets loaded only once by keeping every loaded object in a map. Looks up
objects using the map when referring to them.
Lazy Load
An object that doesn't contain all of the data you need but knows how to get it.
Object-Relational Structural Patterns
Identity Field
Saves a database id field in an object to maintain identity between an in-memory object and a
database row.
Foreign Key Mapping
Maps an association between objects to a foreign key reference between tables.
Association Table Mapping
Saves an association as a table with foreign keys to the tables that are linked by the association.
Dependent Mapping
Has one class perform the database mapping for a child class.
Embedded Value
Maps an object into several fields of another objects table.
Serialized LOB
Saves a graph of objects by serializing them into a single large object (LOB), which it stores in a
database field.
Single Table Inheritance
Represents an inheritance hierarchy of classes as a single table that has columns for all the fields
of the various classes.
Class Table Inheritance
Represents an inheritance hierarchy of classes with one table for each class.
Concrete Table Inheritance
Represents an inheritance hierarchy of classes with one table per concrete class in the hierarchy.
Inheritance Mappers
A structure to organize database mappers that handle inheritance hierarchies.
Object-Relational Metadata Mapping Patterns
Metadata Mapping
Holds details of object-relational mapping in metadata.
Query Object
An object that represents a database query.
Repository
Mediates between the domain and data mapping layers using a collection like interface for accessing
domain objects.
Web Presentation Patterns
Model View Controller
Splits user interface interaction into three distinct roles.
Page Controller
An object that handles a request for a specific page or action on a website.
Front Controller
A controller that handles all requests for a website.
Template View
Renders information into HTML by embedding markers in an html page.
Transform View
A view that processes domain data element by element and transforms it into html.
Two Step View
Turns domain data into html in two steps. First by formatting some kind of logical page, then
rendering the logical page into html.
Application Controller
A centralized point for handling screen navigation and the flow of an application.
Distribution Patterns
Remote Facade
Provides a coarse-grained facade on fine-grained objects to improve efficiency over a network.
Data Transfer Object
An object that carries data between processes in order to reduce the number of method calls.
Offline Concurrency Patterns
Optimistic Offline Lock
Prevents conflicts between concurrent business transactions by detecting a conflict and rolling back
the transaction.
Pessimistic Offline Lock
Prevents conflicts between concurrent business transactions by allowing only one business
transaction at a time to access data.
Coarse-Grained Lock
Locks a set of related objects with a single lock.
Implicit Lock
Allows framework or layer supertype code to acquire offline locks.
Session State Patterns
Client Session State
Stores session state on the client.
Server Session State
Keeps the session state on a server system in a serialized form.
Database Session State
Stores session data as committed data in the database.
Base Patterns
Gateway
An object that encapsulates access to an external system or resource.
Mapper
An object that sets up a communication between two independent objects.
Layer Supertype
A type that acts as the supertype for all types in its layer.
Separated Interface
Defines an interface in a separate package from its implementation.
Registry
A well known object that other objects can use to find common objects and services.
Value Object
A small simple object, like Money or a Date Range, whose equality isn't based on identity.
Money
Represents a monetary value.
Special Case
A subclass that provides special behavior for particular cases.
Plugin
Links classes during configuration rather than compilation.
Service Stub
Removes dependencies upon problematic services during testing.
Record Set
An in-memory representation of tabular data.
The visitor design pattern allows us to separate an algorithm from the structure that the algorithm works against.
This is one of the easiest ways to adhere to the open/closed principle. because it
allows us to add new algorithms without having to modify the original structure that the algorithm is run against.
The full source code for this entry can be downloaded from here.
The visitor design pattern core interfaces in C#:
1 public interface IVisitable<T>
2 {
3 void accept(IVisitor<T> visitor);
4 }
5
6 public interface IVisitor<T>
7 {
8 void visit(T item);
9 }
example
In the following example, I've defined a structure for a table. A table has many rows, and each row
has a different cell for each column.
I have omitted a lot of details for brevity.
1 public class Table : IVisitable<Row>
2 {
3 ...
4 public void accept(IVisitor<Row> visitor)
5 {
6 rows.each(x => visitor.visit(x));
7 }
8 }
9
10 public class Row : IVisitable<ICell>
11 {
12 ...
13 public void accept(IVisitor<ICell> visitor)
14 {
15 cells.each(x => visitor.visit(x));
16 }
17 }
18
19 public class Column<T> : IColumn
20 {
21 ...
22 public Column(string name)
23 {
24 this.name = name;
25 }
26 }
27
28 public class Cell<T> : ICell
29 {
30 ...
31 public bool IsFor(IColumn otherColumn)
32 {
33 return column.Equals(otherColumn);
34 }
35
36 public T Value { get; private set; }
37
38 public void ChangeValueTo(T value)
39 {
40 Value = value;
41 }
42 }
We can now define different algorithms for traversing the table structure without having to modify
the table structure. In this example the TotalRowsVisitor increments a counter each time it visits a
row.
1 public class TotalRowsVisitor : IVisitor<Row>
2 {
3 public void visit(Row item)
4 {
5 Total++;
6 }
7
8 public int Total { get; set; }
9 }
10
11 var visitor = new TotalRowsVisitor();
12 table.accept(visitor);
13 Console.Out.WriteLine( visitor.Total );
The full source code for this entry can be downloaded from here.
links
The open/closed principle (OCP) is another object oriented principle that simple states:
Classes should be open for extension but closed for modification.
In my last post we
fixed the SRP violation,
but we left a violation of the open/closed principle. The reason this principle is important is
because it helps us design components/classes so that the need for change in the future is reduced.
When building software systems it is much safer to introduce new components rather than altering
existing ones. Each time we change the behavior of an existing component, we increase the
possibility of error in existing classes that depend on that classes behavior.
The code we left off with was this:
1 public class DatabaseGateway
2 {
3 IConnectionFactory connectionFactory;
4 IMapper<IDataReader, IEnumerable<DataRow>> mapper;
5
6 public DatabaseGateway(IConnectionFactory connectionFactory, IMapper<IDataReader, IEnumerable<DataRow>> mapper)
7 {
8 this.connectionFactory = connectionFactory;
9 this.mapper = mapper;
10 }
11
12 public IEnumerable<DataRow> execute(string sql)
13 {
14 using( var connection = connectionFactory.OpenConnection())
15 {
16 var command = connection.CreateCommand();
17 command.CommandText = sql;
18 command.CommandType = CommandType.Text;
19 return mapper.MapFrom(command.ExecuteReader());
20 }
21 }
22 }
Each time we need to change how a query is executed against the database, we need to modify the
DatabaseGateway. What we would like is to avoid having to modify DatabaseGateway each time we need
to query against the database in a different way. (e.g. if we wanted to execute a stored procedure
instead of raw SQL.)
We can do this by introducing the strategy pattern.
The strategy pattern allows us to change algorithms at runtime.
Instead of handing the "execute" method a raw SQL string, we're going to pass in a query object.
1 public class DatabaseGateway
2 {
3 IConnectionFactory connectionFactory;
4
5 public DatabaseGateway(IConnectionFactory connectionFactory)
6 {
7 this.connectionFactory = connectionFactory;
8 }
9
10 public void execute(IQuery query)
11 {
12 using( var connection = connectionFactory.OpenConnection())
13 {
14 query.execute_using(connection.CreateCommand());
15 }
16 }
17 }
We're now able to create different implementations of IQuery that can each run against the
IDbCommand interface. By inverting control to an object that is handed to us we are able to add
new types of queries to be run against the database in the future without the need to modify the
DatabaseGateway.
1 public interface IQuery
2 {
3 void execute_using(IDbCommand command);
4 }
5
6 public class RawSQLQuery : IQuery
7 {
8 string sql;
9 public RawSQLQuery(string sql)
10 {
11 this.sql = sql;
12 Result = new DataTable();
13 }
14
15 public DataTable Result{ get; private set; }
16
17 public void execute_using(IDbCommand command)
18 {
19 command.CommandText = sql;
20 command.CommandType = CommandType.Text;
21 Result.Load(command.ExecuteReader());
22 }
23 }
24
25 public class RawSQLCommand : IQuery
26 {
27 string sql;
28 public RawSQLQuery(string sql)
29 {
30 this.sql = sql;
31 Result = new DataTable();
32 }
33
34 public DataTable Result{ get; private set; }
35
36 public void execute_using(IDbCommand command)
37 {
38 command.CommandText = sql;
39 command.CommandType = CommandType.Text;
40 command.ExecuteNonQuery();
41 }
42 }
The query objects are our different Strategy object that we can pass to the DatabaseGateway to
execute commands against the database based on the client components needs.
At ARC I recently got to work on a multi touch screen application for a Smart Board. The application is for when guests come to visit the office, they use the touch screen to lookup the person they are here to see, then create a visitor pass for their visit. The application was built in Flash, which is a technology I have almost no experience with. However, they Flash guys were having some trouble getting the multi-touch piece working on the board. That’s when I came in.
I ended up building a TUIO bridge that is an overlay on top of their application. When a touch is recorded I am building up TUIO packets and flushing it to all connected clients on TCP port 3000. We received a version of a TUIO overlay from the guys at SMART but it didn’t work and the code was a procedural mess. I was committed to writing an OO friendly version of the overlay, and so far so good. There were some tiny things that we had to change to get this working. For instance our target machine was a 64 bit copy of Windows 7. Because of this we had to change some registry settings for the SMART board software. This was a pain to figure out but we got some decent help from a developer at SMART Technologies. Here’s a snippet of an email he from the SMART guy.
We replicated the problem on this end with my Windows 7 machine, so I have a fix for you. What was happening is that when you did a second contact, the software was feeding both contacts to the Windows 7 Gesture recognition engine. To bypass this.
FIRST:
Regedit:
HKEY_CURRENT_USER\Software\Classes\Virtual Store\MACHINE\SOFTWARE\Wow6432Node\SMART Technologies\SMART Board Drivers\Board1\IsDoGesture to 0
The key should already exist.
SECOND:
Run SMART Board Control Panel
- Under SMART Hardware Settings\Mouse and Gesture TURN OFF Enable Multitouch Gestures and Enable Single Touch Gestures.
THIRD:
- Restart SMART Board Service so it picks up the new settings. Under SMART Board Control Panel -> About Software and.. -> Tools -> Diagnostics -> Service -> Stop.
And then start it again.
The registry keys for other versions of Windows are:
- Windows Vista/7 (32 bit, UAC on) HKCU\Software\Classes\VirtualStore\Machine\Software\SMART Technologies\SMART Board Drivers\BoardX\ IsDoGesture
- Windows Vista/7 (64 bit, UAC on) HKCU\Software\Classes\VirtualStore\Machine\Software\Wow6432Node\SMART Technologies\SMART Board Drivers\BoardX\ IsDoGesture
- Windows Vista/7 (32 bit, UAC off) HKLM\Software\SMART Technologies\SMART Board Drivers\BoardX\ IsDoGesture
- Windows Vista/7 (64 bit, UAC off) HKLM\Software\Wow6432Node\SMART Technologies\SMART Board Drivers\BoardX\ IsDoGesture
Where X is a board number >= 1.
In order to make sure the overlay was functioning properly, I built a test tool that listens for all the xml that got flushed to TCP port 3000 and displays it in a console application. When building applications like this, it’s much more important to have useful logging rather then depending on a debugger.
The SMART Board API required me to listen to messages on the windows message pump then funnel those message up in to the SMART board sdk, which then gets processed and pumped back to me via event handlers. When a touch is received it gets a unique id assigned to it. The Smart board is only capable of handling two touches at a time, so only 2 id’s ever appear. The recorded touches are flushed down a TCP socket 30 frames per second. This means that as a unique touch is moving across the board, the last known x and y coordinates for that touch is what should be flushed down.
The key to capturing touches and drags was wiring up event handlers for the OnXYDown, OnXYUp, and OnXYMove events.
The TouchTrigger will fire off the touch to any listening observers.
The TUIOProtocol stores updates the recorded touch for each unique touch id. When the timer elapses it tells the TUIOProtocol to publish the changes to a TCP Connection. As the xml is built it tells each touch to append it’s own header and footer to the xml. If it’s Down touch then something gets appended. If it’s an UP touch then nothing gets added.
The UP touch does not append anything. It just symbolizes a gesture where the user has lifted their finger off of the touch surface.

And that’s all folks. Developing an application for the SMART board has been fun. I would love to get an opportunity to build a full blown WPF app on either the SMART board or the SMART table. For more info on the SMART Developer Network.
Download Source
In this post I am going to discuss multi-legged transactions. Multi legged transactions occurs when items are transferred to and from multiple accounts. For example, If I withdraw $100.00 from my chequing account and put $50.00 in to a retirement savings account and the other $50.00 in to a utility payment account. If you would rather just read the source code, I have provided a download.
In order to successfully complete a multi legged transactions, the total of all exchanges must balance to 0. It’s important to remember that Accounts don’t just apply to monetary values. You can have Gas Volume account with a unit of measure in MCF, or an Oil Volume account measured in BOED. When transferring money from a money account to a gas account, you are essentially buying gas which means you must convert money in to it’s equivalent amount of gas at current price of gas. We’ll talk about different strategies of how you can accomplish this.
There are also times when you want to group accounts together to create a hierarchy of accounts. For example, I could have an expenses account which aggregates entries from a utility payment account, a tax account, and a food expenses account. This is a type of Summary Account which can aggregate one or more Accounts. Accounts at their lowest level are called Detail Accounts. Detail accounts track a the entries for a single account.
Let’s start with an example. When transferring funds from one account to another it should increase the balance of the destination account and decrease the balance of the source account. For this example both of our accounts will use the same currency.
Take a look at the “because” block in the above code. We are depositing a quantity of 100 CAD in to one account, and withdrawing a quantity of 100 CAD from another account. This transaction balances to zero, so when we post the transaction it shouldn’t have any problems. Pretty straight forward so far. We’ve made some key design decisions in these tests. Instead of modeling an account just for money, we are using a Quantity object. This allows to potentially withdraw 80 CAD from one account and deposit 1 BOED of oil in to another account. Before jumping in to the Transaction class let’s take a quick peek at Quantity.
Quantity
In our current implementation Quantity’s can be added to one another, and they can be subtracted from one another. Each quantity represents a single amount of something. That something is represented as a Unit Of Measure. For example, 100 Canadian dollars can be represented as a quantity of 100 with a unit of measure of CAD. 1000 BOED of oil can be modeled as a quantity of 1000 with a unit of measure of BOED. 6 MCF of gas can be represented as a quantity of 6 with a unit of measure of MCF. Each unit of measure can be converted to another unit of measure. When we add 100 CAD to 1000 BOED we may want the result to be measured in CAD or BOED. This requires a conversion using the price of oil at the time of conversion. Let’s talk about one strategy to do this using a exchange rate table.
Unit of Measure
We need a way to sneak in a rate table lookup during runtime, usually the way we would do this is by pushing in a domain service to use to lookup the current days rate. What we want to avoid is having our Domain model reaching out to an external third party directly to look up the rates. But we want to be able to provide a rate table lookup strategy at run time.
The “provide_rate" method allows us to push in a rate lookup, in a manner that doesn’t couple us to the implementation. The actual implementation might open up a connection to a remote host and pull down the current rates, or it might cache the rates and serve them. Either way this becomes completely open for extension. We can now drop in different units of measure like BOED, Currency, MCF etc.
Transaction
Ok now let’s get back on track, we were talking about multi legged transactions. When we are building a transaction we need a way to record the potential entries before actually posting them to each respective account. When we deposit or withdraw anything we record Potential transactions. When we post the transaction we ensure that the balance is zero. If it’s all good then, we commit each potential transaction to the respective accounts.
Detail Account
Now I skipped a bunch of tests, but you can download the source to check out the rest. Each potential transaction records the account that is the target of the entry, and whether it was a deposit or a withdrawal.
When the potential transaction is committed it simple adds the equivalent entry to the target account. When the account calculates the balance it sums up each entry. Withdrawal entries decrement the amount, and deposits increase the amount. The balance is returned in the unit of measure that the account manages. If it’s a monetary account, then a monetary quantity is returned.
Download
I am constantly working towards becoming a better OO practitioner. To do so I like to practice by solving problems by trying to stay true to the design principles of OO. My current job is a great source of real world business domains, so this helps with my practicing. In this post I am going to focus on a specific problem on employee compensation. If you prefer to just download the source code, I have included it as a download.
Last year we released a system to the Human Resources department of our company to help them manage the compensation for each employee in the company. As part of our compensation we are all issued a base salary for the year, a target bonus, and a target LTIP (long term incentive plan.)
The bonus is split in half, and issued to employees in January, and June of each year. This is called the H1 and H2 bonuses. The LTIP is also split in half and issued in the spring and fall of each year. This is known as the spring and fall LTIP. Bonus are issued in cash, but LTIP’s are issued as grants. We offer two types of LTIP’s, one called RTU (restricted trust units) and another called PTU (performance trust units). For this article I am going to focus on our RTU grants.
When a grant is issued to an employee, 1/3 of the grant will vest on each anniversary of the date that the grant was issued. For instance, if I was issued a fall LTIP grant of $4500.00 at a unit price of $10.00, then the following year I would be issued 1/3 of the grants value. If the price doubles from $10.00/unit to $20.00/unit then I would receive a payout of $3000.00. When an employee has been working at ARC for 3 years, then they are considered “fully loaded”, which means that during either the spring or fall compensation events, that employee would receive 1/3 of 3 different grants.
So let’s model this. If an employee can have any where between 0 and 3 grants with unvested units available at any time, how can we calculate the current value of that employees LTIP. Let’s start by writing a unit test, and let test driven development guide us.
In the above set of unit tests, I am focusing on a single employees compensation. I’ve awarded that compensation a single grant valued at $4500.00 at the time of grant at a price of $10.00/unit. In each test I am checking to see that the unvested amount is correct at different times in the future. With this design I can now see what an employees compensation looks like in the future and at any point in the past. This is a form of black box testing, I am testing the expected behavior of a single class. I don’t really care what the underlying implementation is. I just want to know that in the end it produces the value that I expect. This type of testing is my preferred style when working in a domain model, it allows for much easier refactoring, less test maintenance and still preserves the expected behavior.
Compensation
Let’s take a look at the Compensation class to see how we can get these tests passing and stick to some fundamental object oriented programming principles.
Compensation is our aggregate root. Within it’s boundary it creates an instance of Grant via a static factory method. It implements a Visitable<T> interface to adhere to the interface segregation principle as well as the open closed principle. By allowing the Compensation to accept visitors it leaves this class closed for modification but still for extension. We can create new implementation of the visitors and pass them to collect the information necessary. In our calculation we are visiting each Grant and telling it to calculate the balance remaining as of a particular date. Notice the message passing, and information hiding. Compensation doesn’t need to “know” about any of Grants “data” it is invoke specific behaviors on Grant instead of picking off values from getters. I prefer not to use getters and setters, not only are they an anti-patterns in object oriented design, but they help produce brittle software. Every time you add a getter or worse, setter you are adding a future maintenance cost to your software. Focus on behavior rather than on data. (*Note: Although I am against getters and setters I do use them when creating mappings for Fluent NHibernate, but mostly only for that reason. I avoid using getters and setters any where else in my code.)
Grant
There’s a couple of things that happen when we create an instance of Grant. First we record that date that the grant was issued on, second we record the unit price, then we purchase units, and finally we apply a vesting frequency. When we record the unit price we are actually tracking the each price change, which allows us to move forward and backwards in time.
The history of each price change is record in the generic History<T>. This will record the date that the change occurred and keeps a stack of these changes. Again, we are pushing message forward. We have also wrapped the primitive double type in a UnitPrice class that allows us to extend double with additional behavior as well as allows to quickly glean the intention rather than the implementation. If we were to store dollars and units in primitive types, there’s little that blocks us from accidentally adding these two values together. This is just now how Money and UnitPrice behave with one another. This relationship now become explicit when we use actual classes.
When we purchase a certain amount of units, we look up the current unit price, and purchase as many units as we can for the dollars given. Notice how it’s the UnitPrice class that is calculating the number of Units that can be awarded for a certain amount of Money. We then combine those Units with the existing number of Units already awarded to this grant. The Unit Price History allows us to look up the most relevant Unit Price for any given date.
The final balance calculation looks up the unit price for the given date and calculates the total monetary value for the unit that have not expired. We iterate through each expiration and accumulate the units that have not vested. Let’s take a look at how that is done.
Vest
Each Vest has a date that the vest occurs. In our example this happens on each anniversary of the original grant date until each 1/3 has completely vested. To calculate the unit remaining we check to see if the vest expired before the given date. If so then 1/3 has expired. If not then we take the total units available and divide that by 1/3. We have a Fraction interface so that if in the future the rules need to changes from 1/3 to 1/12 we can accommodate that.
In this post I hope that I have given you an opportunity to see the benefit of object oriented modeling. By modeling real world business processes as closely to the real thing, we allow for change, in fact we embrace it. We make the code easy to read and hopefully easy to understand. The small pieces are easier to digest and get new team members up to speed on the core domain much faster. The way we name our classes and methods should be intention revealing and mimic the language used in the core business domain. Focusing on behavior rather than data, allows us to achieve things in a model that a data model simply cannot easily do. I have done my best to illustrate some of the principles of object oriented design such as “Tell don’t ask”, “Single Responsibility Principle”, “Open/Closed Principle”, “Interface Segregation Principle”.
Download
A few months ago I finished reading Pattern Oriented Software Architecture Volume 1. This was an absolutely awesome book. Just about all the patterns in the book target stateful applications, which was just what I was looking for. Some of my favorite patterns were "Pipes and Filters", "Proxy", and "Command Processor".

The book starts off with a great discussion on what a pattern is, what makes a pattern, and why they are useful. Then it goes through a catalog of patterns and offers examples for each. Then it goes on to discuss pattern systems, the patterns community and where patterns are going.
Proxy
The book broke down the proxy pattern in to several different types of proxies. They are:
- Remote Proxy: Clients of remote components should be sheilded from network addresses and inter-process communication protocols.
- Protection Proxy: Components must be protected from unauthorized access.
- Cache Proxy: Multiple local clients can share results from remote components.
- Synchronization Proxy: Multiple simultaneous accesses to a component must be synchronized.
- Counting Proxy: Accidental deletion of components must be prevented or usage statistics collected.
- Virtual Proxy: Processing or loading a component is costly, while partial information about the component may be sufficient.
- Firewall Proxy: Local clients should be protected from the outside world.
In the .NET realm the Castle Dynamic Proxy project makes it pretty darn easy to implement some of the different types of pattern proxies.
The book described 2 major liabilities of the Proxy pattern. It is less efficient due to the indirection, and it can be overkill. Although the proxy pattern is very much like the decorator pattern the major difference between the two is their intent. The decorator adds functionality, and the proxy frees the original from very specific housekeeping code.
Command Processor
Separates the request for a services from its execution. A command processor component manages requests as separate objects, schedules their execution, and provides additional services such as the storing of request objects for later undo.
Let's take a look at an asynchronous command processor that I wrote quite some time ago. AsynchronousCommandProcessor
The way it works is that one thread is placing commands to execute in to a queue, and another thread is processing the commands waiting on the queue. This is useful for keeping the user interface thread responsive, and allows for scheduling long running background tasks.
To see an example of an application using this technique check out my Mo Money application.
If you develop Windows Forms or WPF based applications than I highly recommend that you pick up this book. It is excellent!
I took some time today to pull down the source code for SvnBridge today, and man, I was blown away. I started at Program.cs and made it to line 25 Bootstrapper.Start(). From there I went on to look at the hand rolled container, then the ProxyFactory.
In order for me to fully grasp the System.Runtime.Remoting API for creating proxies I had to re-write the code from SVN Bridge.... I just had too... it's just how I learn. It's like tracing over cartoons when you're a kid. I still do it!
In case you're interested, the attached code is the sample I put together that is derived from the source code of SvnBridge. If you haven't checked out the source for the project, you really should.
Pretty cool stuff.... Hopefully, this helps out anyone else who's just as curious
My reduced sample source code...
1 private static void Main(string[] args)
2 {
3 var marshal_mathers = new Person("marshall mathers");
4 var some_celebrity = ProxyFactory.CreateIPerson>(marshal_mathers, new MyNameIsSlimShadyInterceptor());
5
6 try
7 {
8 var name = some_celebrity.what_is_your_name();
9 name.should_be_equal_to("slim shady");
10 }
11 catch (Exception e)
12 {
13 Console.Out.WriteLine(e);
14 }
15 Console.Out.WriteLine("will the real slim shady please stand up...");
16 Console.In.ReadLine();
17 }
In my last post I briefly mentioned how we were wiring some components in to our container. The syntax looked like the following:
1 container.AddProxyOf(
2 new ReportPresenterTaskConfiguration(),
3 new ReportPresenterTask(
4 Lazy.Load<IReportDocumentBuilder>(),
5 Lazy.Load<IApplicationSettings>())
6 );
We're using Castle Windsor under the hood, but we have an abstraction over it that allows us to configure it as we like. Even switching the underlying implementation. Which we did, from our hand rolled container to Castle Windsor. The implementation of the above method looks as follows:
1 public void AddProxyOf<Interface, Target>(IProxyConfiguration<Interface> configuration, Target instance) where Target : Interface
2 {
3 var builder = new ProxyBuilder<Interface>();
4 configuration.Configure(builder);
5 AddInstanceOf(builder.CreateProxyFor(instance));
6 }
Wikipedia defines the Proxy design pattern as:
A proxy, in its most general form, is a class functioning as an interface to another thing.
To understand the ProxyBuilder implementation you can checkout JP's strongly typed selective proxies. The "AddProxyOf" method creates an instance of a proxybuilder. It then passes it to the configuration to allow it to configure the proxy builder before building the proxy. Then it registers the proxy as a singleton in to the container.
1 public interface IConfiguration<T>
2 {
3 void Configure(T item_to_configure);
4 }
5
6 public interface IProxyConfiguration<T> : IConfiguration<IProxyBuilder<T>>
7 {
8 }
In this case the proxy configuration looks like:
1 public class ReportPresenterTaskConfiguration : IProxyConfiguration<IReportPresenterTask>
2 {
3 public void Configure(IProxyBuilder<IReportPresenterTask> builder)
4 {
5 var constraint = builder.AddInterceptor<DisplayProgressBarInterceptor>();
6 constraint.InterceptOn.RetrieveAuditReport();
7 }
8 }
This guy adds a progress bar interceptor, that displays a progress bar as the report is getting generated via the "RetrieveAuditReport" method on the IReportPresenterTask.
Patterns of Enterprise Application Architecture defines Lazy Load as:
An object that doesn't contain all of the data you need but knows how to get it.
A while back I was trying to figure out how to lazy load objects from a container, so that I didn't need to depend on the objects dependencies needing to be wired up in the correct order. The syntax I was looking for was something like the following....
1 container.AddProxyOf(
2 new ReportPresenterTaskConfiguration(),
3 new ReportPresenterTask(
4 Lazy.Load<IReportDocumentBuilder>(),
5 Lazy.Load<IApplicationSettings>())
6 );
Lazy.Load will return a proxy in place of an actual implementation. This is just a temporary place holder that will forward the calls to the actual implementation. It wont load an instance of the actual type until the first time a call is made to it.
1 public class when_calling_a_method_with_no_arguments_on_a_lazy_loaded_proxy : lazy_loaded_object_context
2 {
3 [Observation]
4 public void should_forward_the_original_call_to_the_target()
5 {
6 target.should_have_been_asked_to(t => t.OneMethod());
7 }
8
9 protected override void establish_context()
10 {
11 target = dependency<ITargetObject>();
12
13 test_container
14 .setup_result_for(t => t.find_an_implementation_of<ITargetObject>())
15 .will_return(target)
16 .Repeat.Once();
17 }
18
19 protected override void because_of()
20 {
21 var result = Lazy.Load<ITargetObject>();
22 result.OneMethod();
23 }
24
25 private ITargetObject target;
26 }
So when the method "OneMethod" is called on the proxy. It should forward the call to the target, which can be loaded from the container. The implementation depends on Castle DynamicProxy, and looks like the following...
1 public static class Lazy
2 {
3 public static T Load<T>() where T : class
4 {
5 return create_proxy_for<T>(create_interceptor_for<T>());
6 }
7
8 private static LazyLoadedInterceptor<T> create_interceptor_for<T>() where T : class
9 {
10 Func<T> get_the_implementation = resolve.dependency_for<T>;
11 return new LazyLoadedInterceptor<T>(get_the_implementation.memorize());
12 }
13
14 private static T create_proxy_for<T>(IInterceptor interceptor)
15 {
16 return new ProxyGenerator().CreateInterfaceProxyWithoutTarget<T>(interceptor);
17 }
18 }
19
20 internal class LazyLoadedInterceptor<T> : IInterceptor
21 {
22 private readonly Func<T> get_the_implementation;
23
24 public LazyLoadedInterceptor(Func<T> get_the_implementation)
25 {
26 this.get_the_implementation = get_the_implementation;
27 }
28
29 public void Intercept(IInvocation invocation)
30 {
31 var method = invocation.GetConcreteMethodInvocationTarget();
32 invocation.ReturnValue = method.Invoke(get_the_implementation(), invocation.Arguments);
33 }
34 }
35
36 public static class func_extensions
37 {
38 public static Func<T> memorize<T>(this Func<T> item) where T : class
39 {
40 T the_implementation = null;
41 return () => {
42 if (null == the_implementation) {
43 the_implementation = item();
44 }
45 return the_implementation;
46 };
47 }
48 }
"resolve" is a static gateway to the underlying IDependencyRegistry. This idea was totally inspired by JP's strongly typed selective proxies. If you haven't already, you should definitely check it out.
Download the source.
In Patterns of Enterprise Application Architecture, the Unit of Work design pattern is defined as:
Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems.
NHibernate seems to have a great implementation of the unit of work, but understanding when to start and commit the unit of work without repeating yourself can be a little tricky. One thing we've been doing is starting a unit of work using an interceptor.
1 [Interceptor(typeof (IUnitOfWorkInterceptor))]
2 public class AccountTasks : IAccountTasks
3 {
4 public bool are_valid(ICredentials credentials)
5 {
6 ...
7 }
8 }
Account tasks is a service layer piece, that is decorated with an interceptor that will begin and commit a unit of work.
1 public interface IUnitOfWorkInterceptor : IInterceptor
2 {
3 }
4
5 public class UnitOfWorkInterceptor : IUnitOfWorkInterceptor
6 {
7 private readonly IUnitOfWorkFactory factory;
8
9 public UnitOfWorkInterceptor(IUnitOfWorkFactory factory)
10 {
11 this.factory = factory;
12 }
13
14 public void Intercept(IInvocation invocation)
15 {
16 using (var unit_of_work = factory.create()) {
17 invocation.Proceed();
18 unit_of_work.commit();
19 }
20 }
21 }
The interceptor starts a new unit of work, before proceeding with the invocation. If no exceptions are raised the unit of work is committed. If a unit of work is already started, the unit of work factory returns an empty unit of work. This ensures that if a service layer method calls into another method that it doesn't start another unit of work.
1 public interface IUnitOfWorkFactory : IFactory<IUnitOfWork>
2 {
3 }
4
5 public class UnitOfWorkFactory : IUnitOfWorkFactory
6 {
7 private readonly IApplicationContext context;
8 private readonly IDatabaseSessionFactory factory;
9 private readonly TypedKey<ISession> key;
10
11 public UnitOfWorkFactory(IApplicationContext context, IDatabaseSessionFactory factory)
12 {
13 this.context = context;
14 this.factory = factory;
15 key = new TypedKey<ISession>();
16 }
17
18 public IUnitOfWork create()
19 {
20 if (unit_of_work_is_already_started()) {
21 return new EmptyUnitOfWork();
22 }
23
24 return create_a_unit_of_work().start();
25 }
26
27 private bool unit_of_work_is_already_started()
28 {
29 return context.contains(key);
30 }
31
32 private IUnitOfWork create_a_unit_of_work()
33 {
34 var session = factory.create();
35 context.add(key, session);
36 return new UnitOfWork(session, context);
37 }
38 }
The implementation of the repository pulls the active session from the application context.
1 public class DatabaseRepository<T> : IRepository<T>
2 {
3 private readonly IApplicationContext context;
4 private readonly IKey<ISession> session_key;
5
6 public DatabaseRepository(IApplicationContext context)
7 {
8 this.context = context;
9 session_key = new TypedKey<ISession>();
10 }
11
12 public IQueryable<T> all()
13 {
14 return the_current_session().Linq<T>();
15 }
16
17 public void save(T item)
18 {
19 the_current_session().SaveOrUpdate(item);
20 }
21
22 public void delete(T item)
23 {
24 the_current_session().Delete(item);
25 }
26
27 private ISession the_current_session()
28 {
29 var current_session = context.get_value_for(session_key);
30 if (null == current_session || !current_session.IsOpen) {
31 throw new NHibernateSessionNotOpenException();
32 }
33 return current_session;
34 }
35 }
36
For more information on Interceptors check out the Castle stack...
Validation is a tough subject. One that I'm constantly trying to think of better ways of doing. Some suggest that all validation should occur in the domain, and some prefer to check if the object is valid before proceeding. I lean towards the idea of not allowing your objects to enter an invalid state. So far the easiest approach I have found to do this is to raise meaningful exceptions in the domain to ensure this.
However, when there are several reasons why an object can be considered "invalid" and, those reasons need to be reflected in the UI, I haven't been able to figure out a clean way to do this in the domain. Suggestions are welcome.
Here's an approach that we've taken to some of our validation, when user input needs to be checked so that we can provide meaningful error messages to the end user.
First we have 2 core validation interfaces:
1 public interface IValidationResult
2 {
3 bool IsValid { get; }
4 IEnumerable<string> BrokenRules { get; }
5 }
and
1 public interface IValidation<T>
2 {
3 IValidationResult Validate(T item);
4 }
The IValidation is in essence a form of a Specification. Now to collect the errors we use a
[visitor](http://mokhan.ca/oo/designpatterns/2010/12/14/the-visitor-design-pattern.html). The following are the core [visitor](http://mokhan.ca/oo/designpatterns/2010/12/14/the-visitor-design-pattern.html) interfaces.
1 public interface IVisitor<T>
2 {
3 void Visit(T item_to_visit);
4 }
5
6 public interface IValueReturningVisitor<TypeToVisit, TypeToReturn> : IVisitor<TypeToVisit>
7 {
8 void Reset();
9 TypeToReturn Result { get; }
10 }
We have an implementation of a IValueReturningVisitor that collects errors from visiting IValidations, then returns a validation result.
1 public class ErrorCollectingVisitor<T> : IValueReturningVisitor<IValidation<T>, IValidationResult>
2 {
3 readonly T item_to_validate;
4 readonly List<string> results;
5
6 public ErrorCollectingVisitor(T item_to_validate)
7 {
8 this.item_to_validate = item_to_validate;
9 results = new List<string>();
10 }
11
12 public void Visit(IValidation<T> item_to_visit)
13 {
14 var validation_result = item_to_visit.Validate(item_to_validate);
15 if (!validation_result.IsValid)
16 {
17 results.AddRange(validation_result.BrokenRules);
18 }
19 }
20
21 public void Reset()
22 {
23 results.Clear();
24 }
25
26 public IValidationResult Result
27 {
28 get { return new ValidationResult(results.Count == 0, results); }
29 }
30 }
And a handy extension method for returning the value from visiting a set of validations.
1 public static Result ReturnValueFromVisitingAllItemsWith<TypeToVisit, Result>(this IEnumerable<TypeToVisit> items_to_visit, IValueReturningVisitor<TypeToVisit, Result> visitor)
2 {
3 visitor.Reset();
4 items_to_visit.Each(x => visitor.Visit(x));
5 return visitor.Result;
6 }
An example of the usage for the visit can be seen below:
1 public IValidationResult Validate(IUser user)
2 {
3 return userValidations
4 .Select(x => x as IValidation<IUser>)
5 .ReturnValueFromVisitingAllItemsWith(new ErrorCollectingVisitor<IUser>(user));
6 }
When building up a tree view that represents the directory structure of a file system, like the windows explorer, my first reaction was to use recursion to traverse the file system and build up a tree. I quickly found that doing something like that is a time consuming process, and required some optimization.
I came up with what I like to call the recursive command. Each Tree Node item on a tree view is bound to a command to execute. The command looks like this...
1 public interface ITreeNodeClickedCommand {
2 void Execute(ITreeNode node);
3 }
When the command is executed, the command gets an opportunity to modify the state of the tree node that was clicked. In this case I wanted to lazy load the sub directories of a node that was clicked. The command implementation looks like this...
1 public interface IAddFoldersCommand : ITreeNodeClickedCommand {}
2
3 public class AddFoldersCommand : IAddFoldersCommand {
4 private readonly DirectoryInfo the_current_directory;
5 private bool has_executed;
6
7 public AddFoldersCommand(DirectoryInfo the_current_directory) {
8 this.the_current_directory = the_current_directory;
9 }
10
11 public void Execute(ITreeNode node) {
12 if (!has_executed) {
13 foreach (var directory in the_current_directory.GetDirectories()) {
14 node.Add(new TreeNodeItem(directory.Name, ApplicationIcons.Folder, new AddFoldersCommand(directory)));
15 }
16 }
17 has_executed = true;
18 }
19 }
20
This command is executed each time the tree node that it is bound too is clicked, but will only build up the child tree node items once. Each of the child tree nodes are bound to a new instance of the same command. Hence, what I like to call the recursive command.
For more information on the command pattern check out WikiPedia's write up.
*Update 11:30 am MST, Friday, August. 01, 2008
After a little more inspection, I realized I was doing nothing more than just visiting each tree node item on the demand. Visitors are known to be great for recursive structures.... so ix-nay on the ecursive-ray ommand-kay.
The revised version:
1 public interface IAddFoldersToTreeVisitor : ITreeNodeVisitor
2 {
3 }
4
5 public class AddFoldersToTreeVisitor : IAddFoldersToTreeVisitor
6 {
7 private readonly DirectoryInfo the_current_directory;
8 private bool has_executed;
9 private readonly IAddFilesToTreeVisitor add_files_visitor;
10 private readonly IAddFoldersCommandFactory factory;
11
12 public AddFoldersToTreeVisitor(DirectoryInfo the_current_directory, IAddFoldersCommandFactory factory,
13 IAddFilesToTreeVisitor add_files_visitor)
14 {
15 this.the_current_directory = the_current_directory;
16 this.factory = factory;
17 this.add_files_visitor = add_files_visitor;
18 }
19
20 public void Visit(ITreeNode node)
21 {
22 if (!has_executed)
23 {
24 foreach (var directory in the_current_directory.GetDirectories())
25 {
26 node.Add(directory.Name, ApplicationIcons.Folder, factory.CreateFor(directory));
27 }
28 add_files_visitor.PreparedWith(the_current_directory);
29 add_files_visitor.Visit(node);
30 }
31 has_executed = true;
32 }
33 }
links
I just finished reading...
 | Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley Professional Computing Series) by Erich Gamma, Richard Helm, Ralph Johnson, John M. Vlissides Read more about this title... |
It's about time I read this book... This catalog contains 23 patterns with examples in C++. I enjoyed reading this book. I found at times that my mind started to drift off, but then there were moments when I would forget where I was and miss my bus stop. (Ok one moment!)
I enjoyed reading the discussion on OO more then anything else in this book. The examples are a little dated but for it's time the catalog is awesome. Although I've been wanting to read this book for a while I preferred "Head First Design Patterns", mostly because it was easy to read. (I call it the comic book for dev's)
As usual, here are some quotes from the book that I really enjoyed.
"When an abstraction can have one of several possible implementations, the usual way to accommodate them is to use inheritance. An abstract class defines the interface to the abstraction, and concrete subclasses implement it in different ways. But this approach isn't always flexible enough. Inheritance binds an implementation to the abstraction permanently, which makes it difficult to modify, extend and reuse abstractions and implementations independently."
"Studies of expert programmers for conventional languages have shown that knowledge and experience isn't organized simply around syntax but in larger conceptual structures such as algorithms, data structures and idioms, and plans for fulfilling a particular goal. Designers probably don't think about the notation they're using for recording the design as much as they try to match the current design situation against plans, algorithms, data structures, and idioms they have learned in the past."
"These design patterns can also make you a better designer. They provide solutions to common problems. If you work with object-oriented systems long enough, you'll probably learn these design patters on your own. But reading the book will help you learn them much faster. Learning these patterns will help a novice act more like an expert."
"To continue to evolve, the software must be reorganized in a process known as refactoring. This is the phase in which frameworks often emerge. Refactoring involves tearing apart classes into special- and general-purpose components, moving operations up or down the class hierarchy, and rationalizing the interfaces of classes. This consolidation phase produces many new kinds of objects, often by decomposing existing objects and using object composition instead of inheritance. Hence black-box reuse replaces white-box reuse. The continual need to satisfy more requirements along with the need for more reuse propels object-oriented software through repeated phases of expansion and consolidation - expansion as new requirements are satisfied, and consolidation as the software becomes more general."
I've got a beef with enums. When I see them, I cringe... which is quite different from my days in C, where I couldn't live without enums and structs. That's another story...
"Flyweight: Use sharing to support large numbers of fine-grained objects efficiently" - Design Patterns
 | Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley Professional Computing Series) by Erich Gamma, Richard Helm, Ralph Johnson, John M. Vlissides Read more about this title... |
Why do some of us quickly jump to enums? In procedural languages it makes sense. It's giving a type code a human readable meaning. So instead of having to stare at type code 1, everywhere you can use State.Acknowledgement, which is a lot easier to understand ... what does 1 mean again?
But in an OO language, I feel dirty when I see enums. The argument of using it for bitwise operations and the Flags attribute is weak. Create a composite!
1 [Flags]
2 public enum Digits {
3 Zero = 0x00,
4 One = 0x01,
5 Two = 0x02,
6 Three = 0x03,
7 Four = 0x04,
8 Five = 0x05,
9 Six = 0x06,
10 Seven = 0x07,
11 Eight = 0x08,
12 Nine = 0x09
13 }
14
15 [Test]
16 public void Should_be_equal_to_2_digits() {
17 Digits digits = Digits.Six | Digits.One;
18 Assert.IsTrue( Digits.Six == (digits & Digits.Six) );
19 Assert.IsTrue( Digits.One == (digits & Digits.One) );
20 }
Weak... do you really want to use a bitwise & to check if a certain digit is enabled. I don't. I'm going to use the following 2 tests to squash the enum into a first class component, with some smarts to it.
1 [Test]
2 public void should_be_able_to_add_a_single_digit() {
3 INumberBuilder builder = CreateSUT( );
4 builder.Add( Digits.One );
5 Assert.AreEqual( new Number( 1 ), builder.Build( ) );
6 }
7
8 [Test]
9 public void should_be_able_to_form_a_number_with_more_than_one_digit() {
10 INumberBuilder builder = CreateSUT( );
11 builder.Add( Digits.One );
12 builder.Add( Digits.Nine );
13 Assert.AreEqual( new Number( 19 ), builder.Build( ) );
14 }
My current NumberBuilder implementation looks like this (it sucks but it works):
1 public class NumberBuilder : INumberBuilder {
2 public void Add( Digits digit ) {
3 numberBeingBuilt += Convert.ToString( Convert.ToInt32( digit ) );
4 }
5
6 public INumber Build() {
7 return new Number( Convert.ToInt32( numberBeingBuilt ) );
8 }
9
10 private string numberBeingBuilt;
11 }
I'm going to start off by creating some Flyweights.
1 public class Digits {
2 public static readonly IDigit Eight = new Digit( 8 );
3 public static readonly IDigit Five = new Digit( 5 );
4 public static readonly IDigit Four = new Digit( 4 );
5 public static readonly IDigit Nine = new Digit( 9 );
6 public static readonly IDigit One = new Digit( 1 );
7 public static readonly IDigit Seven = new Digit( 7 );
8 public static readonly IDigit Six = new Digit( 6 );
9 public static readonly IDigit Three = new Digit( 3 );
10 public static readonly IDigit Two = new Digit( 2 );
11 public static readonly IDigit Zero = new Digit( 0 );
12
13 public class Digit : IDigit {
14 public Digit( int digitToRepresent ) {
15 _digitToRepresent = digitToRepresent;
16 }
17
18 public override string ToString() {
19 return _digitToRepresent.ToString( );
20 }
21
22 private readonly int _digitToRepresent;
23 }
24 }
My compiler is telling me that the Add method on my builder currently accepts a parameter of type "Digits", so I'm going to change the signature to accept a parameter of type IDigit.
1 public interface INumberBuilder {
2 void Add( Digits digit );
3 INumber Build();
4 }
To...
1 public interface INumberBuilder {
2 void Add( IDigit digit );
3 INumber Build();
4 }
Let's update the NumberBuilder implementation to:
1 public class NumberBuilder : INumberBuilder {
2 public NumberBuilder() {
3 _digitsOfNumberBeingBuilt = new List< IDigit >( );
4 }
5
6 public void Add( IDigit digit ) {
7 _digitsOfNumberBeingBuilt.Add( digit );
8 }
9
10 public INumber Build() {
11 return new Number( CreateIntegerFrom( _digitsOfNumberBeingBuilt ) );
12 }
13
14 private int CreateIntegerFrom( IEnumerable< IDigit > digitsOfNumberBeingBuilt ) {
15 StringBuilder builder = new StringBuilder( );
16 foreach ( IDigit digit in digitsOfNumberBeingBuilt ) {
17 builder.Append( digit );
18 }
19 return Convert.ToInt32( builder.ToString( ) );
20 }
21
22 private IList< IDigit > _digitsOfNumberBeingBuilt;
23 }
I run the tests and they pass, sweet. But I'm not happy with the current implementation, so I look for other potential refactorings. I decide to forward the digit to append right to the number, the number can take care of how to append the digit, rather then having the builder doing so. The builder now looks like:
1 public class NumberBuilder : INumberBuilder {
2 public NumberBuilder() {
3 _numberBeingBuilt = new Number( 0 );
4 }
5
6 public void Append( IDigit digit ) {
7 _numberBeingBuilt = _numberBeingBuilt.Append( digit );
8 }
9
10 public INumber Build() {
11 return _numberBeingBuilt;
12 }
13
14 private INumber _numberBeingBuilt;
15 }
And Number looks like:
1 public class Number : INumber, IEquatable< Number > {
2 public Number() : this( 0 ) {}
3
4 public Number( int numberToRepresent ) {
5 _numberToRepresent = numberToRepresent;
6 }
7
8 public INumber Append( IDigit digit ) {
9 return new Number( ( _numberToRepresent*10 ) + digit.Value( ) );
10 }
11
12 public bool Equals( Number number ) {
13 if ( number == null ) {
14 return false;
15 }
16 return _numberToRepresent == number._numberToRepresent;
17 }
18
19 public override string ToString() {
20 return _numberToRepresent.ToString( );
21 }
22
23 public override bool Equals( object obj ) {
24 if ( ReferenceEquals( this, obj ) ) {
25 return true;
26 }
27 return Equals( obj as Number );
28 }
29
30 public override int GetHashCode() {
31 return _numberToRepresent;
32 }
33
34 private readonly int _numberToRepresent;
35 }
To wrap this up, Number aggregates digits, the enum got dropped and was replaced by a class. There's still more refactorings that can occur, but the point is that a full blown component is much easier to extend then an enum...
For more info check out "Replace Type Code with Class" from...
 |
Refactoring: Improving the Design of Existing Code (The Addison-Wesley Object Technology Series)
by Martin Fowler, Kent Beck, John Brant, William Opdyke, Don Roberts
Read more about this title... |
Soure:
WebForms is an awkward marriage between a Page Controller and a Template View. In the Web Forms model the Template View (aspx page) inherits from the Page Controller (code behind).
Patterns of Enterprise Application Architecture defines the Page Controller as:
"An object that handles a request for a specific page or action on a web site." - PoEAA
In this example I've separated the Page Controller from the Template View, because... mostly because I was bored and thought this would be a great way to better understand the patterns. So let's get started...
I defined a layer super type for all page controllers defined as :
1 public interface IPageController : IHttpHandler {
2 void Execute();
3 }
The IPageController could have very well been called and Page Command because in this implementation I'm not concerned about having separate behaviors for GET and POST method requests. If this example were to evolve I might choose to separate the "Execute()" method into "ProcessGetRequest()" and "ProcessPostRequest()".
The IPageController type inherits IHttpHandler in order to register this page controller with ASP.NET to receive all requests for a particular path. In this case this handler is registered in the web.config for all requests to the "DisplayAllCustomers.aspx" page.
1 <httpHandlers>
2 <add
3 verb="*"
4 path="DisplayAllCustomers.aspx"
5 validate="false"
6 type="PlayingWithPageControllers.Web.Controllers.DisplayAllCustomersController, PlayingWithPageControllers"/>
7 </httpHandlers>
If I wanted to get a little more nitty, gritty I could have specified only GET Http method's are handled by this handler.
Moving on.... The PageController base type for all controllers looks like:
1 public abstract class PageController : IPageController {
2 public void ProcessRequest( HttpContext context ) {
3 Execute( );
4 }
5
6 public bool IsReusable {
7 get { return true; }
8 }
9
10 public abstract void Execute();
11 }
And finally our "DisplayAllCustomersController" component looks like:
1 public class DisplayAllCustomersController : PageController, IDisplayAllCustomersController {
2 public DisplayAllCustomersController( IDisplayAllCustomersView view, ICustomerTasks tasks ) {
3 _view = view;
4 _tasks = tasks;
5 }
6
7 public override void Execute() {
8 _view.AddToBag( _tasks.AllCustomers( ) );
9 _view.Render( );
10 }
11
12 private readonly IDisplayAllCustomersView _view;
13 private readonly ICustomerTasks _tasks;
14 }
And voila all requests to "DisplayAllCustomers.aspx" are handled by the DisplayAllCustomersController which pulls information from the model and fires it off to the template view to be rendered.
The Template View Pattern is defined as:
"Renders information into HTML by embedding markers in an HTML page." - PoEAA
Our template view for "AllCustomers.aspx" looks like this:
1 <table>
2 <thead>
3 <tr>
4 <td>First Name:</td>
5 <td>Last Name:</td>
6 </tr>
7 </thead>
8 <tbody>
9 <% foreach ( DisplayCustomerDTO dto in ViewBagLocator.For(
10 ViewBagKeys.DisplayCustomers ) ) {%>
11 <tr>
12 <td><%= dto.FirstName() %></td>
13 <td><%= dto.LastName( ) %></td>
14 </tr>
15 <% } %>
16 </tbody>
17 </table>
This separates the Template view from having any knowledge of the Page Controller. The Page controller has the responsibility of pulling information from the model to pass along to the appropriate view.
All access to the current context and the ASP.NET pipeline has been isolated to the HttpGateway which abstracts the ASP.NET facilities available through a condensed client interface.
1 public interface IHttpGateway {
2 void RedirectTo( IView view );
3
4 void AddItemWith< T >( IViewBagKey< T > key, T itemToAddToBag );
5
6 T FindItemFor< T >( IViewBagKey< T > key );
7 }
Now that I think about it, another step that I could have taken would have to shield the page controllers from having any knowledge of "IHttpHandler", which would have further isolated the ASP.NET infrastructure from the rest of the web presentation layer.
Patterns of Enterprise Application Architecture defines a Gateway as:
"An object that encapsulates access to an external system or resource." - PoEAA
1 public class HttpGateway : IHttpGateway {
2 public HttpGateway( IHttpContext context ) {
3 _context = context;
4 }
5
6 public void RedirectTo( IView view ) {
7 _context.Server.Transfer( view.Path( ) );
8 }
9
10 public void AddItemWith< T >( IViewBagKey< T > key, T itemToAddToBag ) {
11 _context.Items.Add( key, itemToAddToBag );
12 }
13
14 public T FindItemFor< T >( IViewBagKey< T > key ) {
15 return ( T )_context.Items[ key ];
16 }
17
18 private readonly IHttpContext _context;
19 }
If you haven't already you should go buy and read, then re-read, then re-read "Patterns of Enterprise Application Architecture by Martin Fowler"
Source: DOWNLOAD THE CODE
So another thought that came to mind was the concept of how to switch views in a winforms application. Bare with me because these are only thought so far and I have yet to read about the actual "Application Controller" pattern in PoEAA.
I've been reading a book on WinForms lately by Chris Sells, the name evades me at the moment but I promise to give you the name in the future. And it tells about the ApplicationContext and how it works and how you can access it.
If you take a look at the overloads for the "Application.Run()" method you'll find one that accepts an ApplicationContext. When you choose the overload that accepts a Form it creates an application context and registers for the form closing event which is when it call Application.Exit().
If you can access the context then you can access the start up form, and if you need to switch user controls on the main form you can try to access the application context to do so. Here's my 30 second brain dump on potentially how this could work... (Warning... I have yet to fully implement this!)
1 public class ApplicationController
2 {
3 private static System.Windows.Forms.ApplicationContext _context;
4 private readonly IScreenRegistry registry;
5
6 public ApplicationController( IScreenRegistry registry )
7 {
8 this.registry = registry;
9 }
10
11 public static void Begin( )
12 {
13 Application.EnableVisualStyles( );
14 Application.SetCompatibleTextRenderingDefault( false );
15 _context = new System.Windows.Forms.ApplicationContext( new Form1( ) );
16 Application.Run( _context );
17 }
18
19 public void Render( IScreen screen )
20 {
21 _context.MainForm.Controls.Add( registry.FindFor( screen ) );
22 }
23 }
Main then becomes an empty shell that delegates to the application controller, when types in the system need to render a new view it can call upon the ApplicationController to take care of that by calling it's Render method and passing in the screen to display. The application controller can then leverage registry to find the user control that's registered for the screen.
Hey, if anyone knows a good book on WinForms patterns of even UI patterns I'd love to hear about it!
Source:
This week while I'm at home on holidays, I've been reading...
This book is amazing, I could probably read it over and over again. The patterns that it presents makes a lot of sense, the actual implementations and examples could probably re-vamped but I'm finding that it's a great starter to trying to understand the concepts.
So today I'm trying to grok this concept of the "IDENTITY MAP". The book defines it as:
"Ensures that each object gets loaded only once by keeping every loaded object in a map. Looks up objects using the map when referring to them."
I put together a quick implementation that I'm using for an assignment I'm writing for school. I'm creating repositories that have 2 dependencies. First dependency is a Data Mapper (not to be confused with a Mapper) and the second is an Identity Map.
As objects are requested from the repository, the repository is checking the identity map to see if an instance has been loaded, if it has it's immediately returned to the caller. If the object is not in the map the repository leverages the data mapper to load the object, then adds it to the map and returns it to the caller.
The Data Mapper is defined as:
"A layer of Mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself." - PoEAA
I created a Layer Supertype to register objects in the map. The Domain Layer Super type demands that domain objects had an ID. The ID is what's getting used to load and register objects into the map.
The Layer Supertype is defined as:
"A type that acts as a the supertype for all types in it's layer." - PoEAA
The Domain Layer Super Type.
1 public interface IDomainObject {
2 long ID();
3 }
My actual implementation of the identity map looks like this...
1 public class IdentityMap> T > : IIdentityMap> T > where T : IDomainObject {
2 public IdentityMap() {
3 _items = new List> T >( );
4 }
5
6 public void Add( T domainObject ) {
7 EnsureObjectHasNotAlreadyBeenAdded( domainObject );
8 _items.Add( domainObject );
9 }
10
11 public T FindObjectWithIdOf( long idOfObjectToFind ) {
12 foreach ( T item in _items ) {
13 if ( item.ID( ).Equals( idOfObjectToFind ) ) {
14 return item;
15 }
16 }
17 return default( T );
18 }
19
20 private void EnsureObjectHasNotAlreadyBeenAdded( T domainObject ) {
21 if ( ContainsObjectWithIdOf( domainObject.ID( ) ) ) {
22 throw new ObjectAlreadyAddedToIdentityMapException( domainObject );
23 }
24 }
25
26 private readonly IList> T > _items;
27 }
One of the benefits I like about the Identity Map is that it acts as an in memory cache for objects loaded from the database. This reduces the number of trips to and from the persistence store.
Source Code
I'd like to talk to you for a moment about my man The Event Aggregator. (Homeboy's been tossin' events for years!)
Martin Fowler defines the Event Aggregator as:
"Channel events from multiple objects into a single object to simplify registration for clients." - Martin Fowler
But he's so much more then that! This pattern comes in handy in state-ful environments, so.. hello WinForms/WPF. Sorry ASP.NET!
What this guy does is creates a single channel to find out what's going on and to raise events. Through the event aggregator you can subscribe to known events in the system as well as raise known events in the system.
Some examples for system wide events are Save, Loading, Shutdown. You can also create concepts for layer specific event aggregators that target certain layers of a system. For example UI only.
1 public class ApplicationEvents {
2 private static readonly IEventAggregator aggregator;
3 public static readonly IEvent Save = new EventRaiser( "Save" );
4 public static readonly IEvent Loading = new EventRaiser( "Loading" );
5
6 static ApplicationEvents( ) {
7 aggregator = new EventAggregator( );
8 aggregator.Register( Save );
9 aggregator.Register( Loading );
10 }
11
12 public static void Raise( IEvent eventToRaise ) {
13 aggregator.RaiseEvent( eventToRaise );
14 }
15
16 public static void SubscribeTo( IEvent eventToSubscribeTo, EventHandler handler ) {
17 aggregator.AddHandler( eventToSubscribeTo.Name, handler );
18 }
19 }
The ApplicationEvents becomes the central point for raising and subscribing to known application wide events. Type can be coupled to the aggregator but not to each other.
Let's start with the concept of a named event. An event is really nothing more then a delegate. In .NET there are 2 delegate signatures that are used for all events. The generic and non generic version of the EventHandler delegate. (Read More... )
A named event is an event with a name. He might look something like this guy?
internal class EventRaiser : IEvent {
public EventRaiser( string name ) {
_name = name;
_handlers = new List< EventHandler >( );
}
public string Name {
get { return _name; }
}
public void Add( EventHandler handler ) {
_handlers.Add( handler );
}
public void Raise( ) {
Raise( null, null );
}
public void Raise( object sender, EventArgs data ) {
foreach ( EventHandler handler in _handlers ) {
if ( handler != null ) {
handler( sender, data );
}
}
}
private readonly string _name;
private readonly IList< EventHandler > _handlers;
}
Underneath the hood it's the aggregator that's maintaining references to all the types that have subscribed to events.
1 public class EventAggregator : IEventAggregator {
2 public EventAggregator( ) {
3 _events = new Dictionary< string, IEvent >( );
4 }
5
6 public void Register( string eventName ) {
7 Register( new EventRaiser( eventName ) );
8 }
9
10 public void Register( IEvent eventToAdd ) {
11 EnsureEventHasntBeenRegistered( eventToAdd );
12 _events.Add( eventToAdd.Name, eventToAdd );
13 }
14
15 public void AddHandler( string eventName, EventHandler handler ) {
16 RetrieveEvent( eventName ).Add( handler );
17 }
18
19 public void RaiseEvent( string withEventName ) {
20 RaiseEvent< EventArgs >( withEventName, null, EventArgs.Empty );
21 }
22
23 public void RaiseEvent( IEvent eventToRaise ) {
24 RaiseEvent< EventArgs >( eventToRaise.Name, null, EventArgs.Empty );
25 }
26
27 public void RaiseEvent< T >( string withEventName, object sender, T data ) where T : EventArgs {
28 RetrieveEvent( withEventName ).Raise( sender, data );
29 }
30
31 private IEvent RetrieveEvent( string eventName ) {
32 if ( _events.ContainsKey( eventName ) ) {
33 return _events[ eventName ];
34 }
35 throw new ArgumentNullException( eventName, "The Event Has Not Been Registered." );
36 }
37
38 private void EnsureEventHasntBeenRegistered( IEvent eventToAdd ) {
39 if ( _events.ContainsKey( eventToAdd.Name ) ) {
40 throw new ArgumentException( "Event name has already been registered", eventToAdd.Name );
41 }
42 }
43
44 private readonly IDictionary< string, IEvent > _events;
45 }
The concept is similar to Juval Lowy's EventHelper class defined in...
One of the many cool things we learned last week was on how to traverse a collection using a visitor.
"...the visitor design pattern is a way of separating an algorithm from an object structure. A practical result of this separation is the ability to add new operations to existing object structures without modifying those structures." - wikipedia
Let's pretend that I've got an exam, and this exam has a bunch of questions and I want to find out how many questions have been completed.
I could throw a method on my IExam type that returns the number of completed questions. Kind of like...
1 public class BadExam : IExam {
2 public BadExam( ) : this( new List> IQuestion >( ) ) {}
3
4 public BadExam( IList> IQuestion > questions ) {
5 _questions = questions;
6 }
7
8 public int GetCompletedQuestions( ) {
9 int completedQuestions = 0;
10 foreach ( IQuestion question in _questions ) {
11 completedQuestions += question.IsComplete( ) ? 1 : 0;
12 }
13 return completedQuestions;
14 }
15
16 private IList> IQuestion > _questions;
17 }
But what happens when I want to find out other statistics about the questions in my exam. I could add additional methods to the IExam type for each type of information that I want to query on, but this would totally violate the Open/Closed Principle.
Let's try to solve the same problem above using a visitor...
1 public class Exam : IExam {
2 public Exam( ) : this( new List> IQuestion >( ) ) {}
3
4 public Exam( IList> IQuestion > questions ) {
5 _questions = questions;
6 }
7
8 public void TraverseUsing( IVisitor> IQuestion > visitor ) {
9 foreach ( IQuestion question in _questions ) {
10 visitor.Visit( question );
11 }
12 }
13
14 private IList> IQuestion > _questions;
15 }
What this allows me to do is create new implementations of IVisitor's that traverse the collection of questions but collect information that it needs.
For example we could have a "CompletedQuestionsVisitor" that keeps track of the number of completed questions.
1 public class CompletedQuestionsVisitor : ICompletedQuestionsVisitor {
2 private int _completedQuestions;
3
4 public void Visit( IQuestion question ) {
5 _completedQuestions += ( question.IsComplete( ) ? 1 : 0 );
6 }
7
8 public int TotalCompletedQuestions( ) {
9 return _completedQuestions;
10 }
11 }
Now I can traverse the internal collection of questions and pick out the information that I need.
What if I wanted to build a tree of specifications and wanted to traverse a collection of items and keep track of only those items that match my composite specification. Introducing the "Specification Visitor".
1 public class SpecificationVisitor> T > : ISpecificationVisitor> T > {
2 private readonly ISpecification> T > _specification;
3 private int _totalMatching;
4
5 public SpecificationVisitor( ISpecification> T > specification ) {
6 _specification = specification;
7 }
8
9 public void Visit( T item ) {
10 _totalMatching += _specification.IsSatisfiedBy( item ) ? 1 : 0;
11 }
12
13 public int TotalMatching( ) {
14 return _totalMatching;
15 }
16 }
Yes it's a little overboard and slightly contrived, but perhaps someone can find a good home for him.
Source Code (2.28MB)
So tonight I decided to spend some time playing with services, principals, identities, and loggers. On Thursday at work a client wanted to be able to log several different events in a system. I remember a while back reading an article on MSDN byOren on Ioc, and I thought I would try to roll something out just to get a feel for who it could work. I still have a lot to learn when it comes to IoC so I put that aside for now.
It all starts at the "AuthenticationService" in a method called "CheckCredentials". It looks something like...
1 public bool CheckCredentials( string userName, string password ) {
2 IUser user = _repository.FindBy( userName );
3 if ( IsMatch( user.Password, password ) ) {
4 ApplyPrincipalToThreadFor( user );
5 return true;
6 }
7 return false;
8 }
This method checks the repository for the user with the matching username and checks to see if the password given matches what's stored for the user in the repository. If it does, a principal is created and applied to the current thread. Passwords really shouldn't be held in memory for long, and would probably better be transferred or computedas a hash, so that the actual password exposure is limited. (There's also a "SecureString" type which I haven't spent much time looking at, but sounds promising!)
Now if I wanted to log all login attempts I canextend this service with a AuthenticationLoggerService decorator. That looks like...
1 public class AuthenticationLoggerService : IAuthenticationService {
2 public AuthenticationLoggerService( IAuthenticationService service, ILogger logger ) {
3 _service = service;
4 _logger = logger;
5 }
6
7 public bool CheckCredentials( string userName, string password ) {
8 _logger.Write( "User Login Attempt: " + userName );
9 return _service.CheckCredentials( userName, password );
10 }
11
12 private readonly IAuthenticationService _service;
13 private readonly ILogger _logger;
14 }
All this type does is log information and delegate to the actual type.
"The Decorator Pattern attaches additional responsibilities to an object dynamically. Decorators provide flexible alternative to subclassing for extending functionality." - Head First Design Patterns
Read more in...
PlayingWithServices.zip (2.28 MB)
I recently came across a problem, and I thought I would try to flex some of my developer muscle to try to solve it. The problem reads as follows:
Basic sales tax is applicable at a rate of 10% on all goods, except books,
food, and medical products that are exempt. Import duty is an additional
sales tax applicable on all imported goods at a rate of 5%, with no
exemptions.
When I purchase items I receive a receipt which lists the name of all the
items and their price (including tax), finishing with the total cost of the
items, and the total amounts of sales taxes paid. The rounding rules for
sales tax are that for a tax rate of n%, a shelf price of p contains
(np/100 rounded up to the nearest 0.05) amount of sales tax.
Write an application that prints out the receipt details for these shopping
baskets...
INPUT:_
Input 1:
1 book at 12.49
1 music CD at 14.99
1 chocolate bar at 0.85
Input 2:
1 imported box of chocolates at 10.00
1 imported bottle of perfume at 47.50
Input 3:
1 imported bottle of perfume at 27.99
1 bottle of perfume at 18.99
1 packet of headache pills at 9.75
1 box of imported chocolates at 11.25
OUTPUT
Output 1:
1 book : 12.49
1 music CD: 16.49
1 chocolate bar: 0.85
Sales Taxes: 1.50
Total: 29.83
Output 2:
1 imported box of chocolates: 10.50
1 imported bottle of perfume: 54.65
Sales Taxes: 7.65
Total: 65.15
Output 3:
1 imported bottle of perfume: 32.19
1 bottle of perfume: 20.89
1 packet of headache pills: 9.75
1 imported box of chocolates: 11.85
Sales Taxes: 6.70
Total: 74.68
==========
To solve this problem I used a composite to calculate taxes. The "TaxComposite" type allows you to bundle several different taxes all in one type. So when calculating taxes, the calculation with iterate through all the taxes and add the calculated tax and return the total value.
1 public class TaxComposite : ITax {
2 public TaxComposite( params ITax[] taxes ) : this( new List< ITax >( taxes ) ) {}
3
4 public TaxComposite( IEnumerable< ITax > taxes ) {
5 _taxes = new List< ITax >( taxes );
6 _amount = CalculateAmount( );
7 _type = CalculateType( );
8 }
9
10 public double Amount {
11 get { return _amount; }
12 }
13
14 public TaxTypes Type {
15 get { return _type; }
16 }
17
18 public IMoney CalculateTaxFor( IMoney price ) {
19 return CalculateTaxFor( price, RoundingDelegateFactory.RoundToNearestTenCents );
20 }
21
22 public IMoney CalculateTaxFor( IMoney price, RoundingStrategy round ) {
23 IMoney total = new Money( );
24 Summary( delegate( ITax tax ) { total = total.Add( tax.CalculateTaxFor( price, round ) ); } );
25 return total;
26 }
27
28 private double CalculateAmount( ) {
29 double amount = 0d;
30 Summary( delegate( ITax tax ) { amount += tax.Amount; } );
31 return amount;
32 }
33
34 private TaxTypes CalculateType( ) {
35 TaxTypes type = TaxTypes.None;
36 Summary( delegate( ITax tax ) { type = type | tax.Type; } );
37 return type;
38 }
39
40 private void Summary( Action< ITax > toDo ) {
41 foreach ( ITax tax in _taxes ) {
42 toDo( tax );
43 }
44 }
45
46 private readonly IList< ITax > _taxes;
47 private readonly double _amount;
48 private readonly TaxTypes _type;
49 }
"The Composite Pattern allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly." - Head First Design Patterns
I used a TaxFactory type to construct the TaxComposite type which gathers all the taxes that match a specified predicate and injects it into the TaxComposite constructor. It looks like...
1 public static class TaxFactory {
2 public static ITax Create( TaxTypes forTaxes ) {
3 return new TaxComposite(
4 Taxes.FindBy( delegate( ITax tax ) { return ( tax.Type & forTaxes ) == tax.Type; } ) );
5 }
The tax type is an enum that uses the flags attribute so that I can enable different bits for different taxes.
1 [Flags]
2 public enum TaxTypes {
3 None = 0x00,
4 Sales = 0x01,
5 Import = 0x02
6 }
Taxes is a static type that contains different types of taxes. The FindBy method allows for different strategies to be passed into to gather different types of taxes based on different critera. The above example returns all the taxes that are enabled in the "forTaxes" argument. FindBy is defined like...
1 public static IEnumerable< ITax > FindBy( Predicate< ITax > condition ) {
2 foreach ( ITax tax in taxes ) {
3 if ( condition( tax ) ) {
4 yield return tax;
5 }
6 }
7 }
I'm not sure if this is the most flexible design, but if i need to make changes to tax rates I can do that in one spot. The only catch is that it requires a re-compile to take a effect. In a full blown implementation I may want to consider using a "service" to retrieve the tax rates. Also, in this implementation in order to add new taxes I have to added it too 2 different locations. The first is the TaxTypes enum and the second is the Taxes static holder class. This leaves a bit of a smell...
The Open-Closed Principle (OCP): Classes should be open for extension, and closed for modification.
The Don't Repeat Yourself Principle (DRY): Avoid duplicate code by abstracting out things that are common and placing those things in a single location.
The Single Responsibility Principle (SRP): Every object in your system should have a single responsibility, and all the objects services should be focused carrying out that single responsibility.
The Liskov Substitution Principle (LSP): Subtypes must be substitutable for their base types. (The LSP is all about well-designed inheritance.)
The Hollywood Principle: Don't call us, we'll call you.
The Law of Demeter (The principle of least knowledge): Only talk to your immediate friends.
Delegation is when you hand over the responsibility for a particular task to another class or method.
Composition allows you to use behavior from a family of other classes, and to change that behavior at runtime.
Aggregation is when one class is used as part of another class, but still exists outside of that other class.
Encapsulate what varies.
Favor composition over inheritance.
Program to interfaces, not implementations.
Strive for loosely coupled designs between objects that interact.
Depend on abstractions. Do not depend on concrete classes.
 | Head First Object-Oriented Analysis and Design: A Brain Friendly Guide to OOA&D (Head First) by Brett D. McLaughlin, Gary Pollice, Dave West
Read more about this title... |
To demo how the Factory Method and Abstract Factory patterns work I've put together an
example in C#.
For this example I've got 2 different Banks, CIBC, and Royal Bank. Each bank offers a chequing and savings account.
Through the use of the Factory Method and Abstract Factory, the sample shows you how to create different types of bank accounts.
"The Factory Method Pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate.
Factory Method lets a class defer instantiation to subclasses." - Head First Design Patterns
IBank has a single method called "GetAccountFactory()" that returns a IBankAccountFactory.
This allows types that implement the interface to specify what type of bank account factory to construct and return.
public interface IBank
{
string Name { get; }
IBankAccountFactory GetAccountFactory( );
}
So CIBC implementation of IBank will return a CIBCBankAccountFactory.
public class CibcBank : Bank, IBank
{
public CibcBank( ) : base( "CIBC" ) {}
public override IBankAccountFactory GetAccountFactory( )
{
return new CibcBankAccountFactory( );
}
}
"The Abstract Factory Pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes."
- Head First Design Patterns
IBankAccountFactory is an abstract factory for creating different types of bank accounts.
In my provided example you'll see that the IBankAccountFactory has two methods defined in it, both of which return an IBankAccount:
- CreateChequingAccount()
- CreateSavingsAccount()
public interface IBankAccountFactory
{
IBankAccount CreateChequingAccount( );
IBankAccount CreateSavingsAccount( );
}
To create a CIBC chequing account, the client code might look something like this:
1 IBank bank = new CibcBank( );
2 IBankAccountFactory factory = bank.GetAccountFactory( );
3 IBankAccount chequingAccount = factory.CreateChequingAccount( );
To create a Royal Bank chequing account, the client code might look something like this:
1 IBank bank = new RoyalBank( );
2 IBankAccountFactory factory = bank.GetAccountFactory( );
3 IBankAccount chequingAccount = factory.CreateChequingAccount( );
Head First Design Patterns (Head First) by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra
Read more about this title...
DesignPatterns.Factory.zip (9.16 KB)
"The State Pattern allows an object to alter its behavior when its internal state changes.
The object will appear to change it's class." - Head First Design Pattern
Head First Design Patterns (Head First)
by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra
Read more about this title...
Let's say I've got a point of sale terminal used for processing financial transactions.
Let's say that at any given time the terminal can be in 1 of 6 states. Those states are:
- **Idle State: During this state an idle message is displayed on the screen of the POS terminal.
- **Card Swiped State: The terminal enters this state when a card is swiped.
- **Amount Entered State: The terminal enters this state when the transaction amount is entered.
- **PIN Entered State: The terminal enters this state when the customer enters their PIN.
- **Processing Transaction State: The terminal enters this state when it connects to a financial processor to process the transaction.
- **Transaction Approved State: The terminal enters this state when the transaction has been process and has been approved.
- **Transaction Rejected State: The terminal enters this state when the transaction was processed but was rejected.
Let's pretend the following is the client code that will use the point of sale terminal to process transactions.
1 IPosTerminal terminal = new PosTerminal( );
2 terminal.SwipeCard( "6278080000008205" );
3 terminal.EnterAmount( 99.99 );
4 terminal.EnterPin( "8012" );
5 terminal.ProcessTransaction( );
6 terminal.PrintReceipt( );
When the PosTerminal is first constructed it is immediate put into an Idle State which displays an idle message to screen.
The PosTerminal has a property of type IState that all the concrete state types implement.
As actions are performed against the PosTerminal, they are delegated to the current state.
1 public void SwipeCard( string cardNumber ) {
2 _currentState.SwipeCard( cardNumber );
3 }
4
5 public void EnterAmount( double amount ) {
6 _currentState.EnterAmount( amount );
7 }
8
9 public void EnterPin( string pin ) {
10 _currentState.EnterPin( pin );
11 }
12
13 public void AuthorizeTransaction( ) {
14 _currentState.ProcessTransaction( );
15 }
16
17 public void PrintReceipt( ) {
18 _currentState.PrintReceipt( );
19 }
20
21 public void ProcessTransaction( ) {
22 _currentState.ProcessTransaction( );
23 }
In this implementation I've made it the concrete state types responsibility to transition to the next state. For example the IdleState might look like:
1 public void SwipeCard( string cardNumber ) {
2 _terminal.Transaction = new PosTransaction( );
3 _terminal.Transaction.Date = DateTime.Now;
4 _terminal.Transaction.CardNumber = cardNumber;
5 _terminal.CurrentState = new CardSwipedState( _terminal );
6 }
7
8 public void EnterAmount( double amount ) {
9 Console.Out.WriteLine( "Please swipe a card first." );
10 }
With the state pattern you can re-order states and alter the implementation of a state with out having to change the subject of the state.
DesignPatterns.State.zip (7.13 KB)
"The Adapter Pattern converts the interface of a class into another interface the clients expect.
Adapter lets classes work together that couldn't otherwise because of incompatible interfaces." - Head First Design Patterns
Head First Design Patterns (Head First)
by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra
Read more about this title...
If you're trying to build a presentation layer that is platform agnostic, you might turn to adapters for simple UI controls.
For example in ASP.NET there is a drop down list control, and in Win Forms there is the Combo Box control.
A quick an easy adapter to the two controls might look like:
public interface IDropDownListAdapter
{
void BindTo( IEnumerable<IDropDownListItem> pairs );
IDropDownListItem SelectedItem { get; }
}
Each drop down list item might look like:
public interface IDropDownListItem
{
string Text { get; }
string Value { get; }
}
A concrete implementation for a Win Forms application might look like:
public class DesktopDropDownList : IDropDownListAdapter
{
public DesktopDropDownList( ComboBox dropDown )
{
_dropDown = dropDown;
_pairs = new Dictionary<string, IDropDownListItem>( );
}
public void BindTo( IEnumerable< IDropDownListItem > pairs )
{
if ( pairs != null )
{
_pairs = new Dictionary< string, IDropDownListItem >( );
foreach ( IDropDownListItem pair in pairs )
{
_dropDown.Items.Add( pair.Text );
_pairs.Add( pair.Text, pair );
}
_dropDown.SelectedIndex = 0;
}
}
public IDropDownListItem SelectedItem
{
get { return !string.IsNullOrEmpty( _dropDown.Text ) ? _pairs[ _dropDown.Text ] : null; }
}
private ComboBox _dropDown;
private IDictionary< string, IDropDownListItem > _pairs;
}
A concrete implementation for a ASP.NET application might look like:
public class WebDropDownList : IDropDownListAdapter
{
public WebDropDownList( DropDownList dropDown )
{
_dropDown = dropDown;
}
public void BindTo( IEnumerable< IDropDownListItem > pairs )
{
if ( pairs != null )
{
foreach ( IDropDownListItem pair in pairs )
{
_dropDown.Items.Add( new ListItem( pair.Text, pair.Value ) );
}
}
}
public IDropDownListItem SelectedItem
{
get { return new DropDownListItem( _dropDown.SelectedItem.Text, _dropDown.SelectedItem.Value ); }
}
private DropDownList _dropDown;
}
And voila... we can write a presentation layer that binds data to an IDropDownListAdapter, without having to be specific to WinForms, ASP.NET, WPF, Silverlight etc.
public Presenter( IView view )
{
_view = view;
}
public void Initialize( )
{
IList< IDropDownListItem > items = new List< IDropDownListItem >( );
items.Add( new DropDownListItem( "Yes", "1" ) );
items.Add( new DropDownListItem( "No", "2" ) );
_view.AreYouHappy.BindTo( items );
}
DesignPatterns.Adapter.zip (4.56 KB)
"The observer pattern defines a one-to-many dependency between objects so that when one object changes state,
all of its dependents are notified and updated automatically." - Head First Design Patterns
What this means is that if you have objects that are interested in changes in another object, you allow the "observers" to register or subscribe to the subject.
In the example provided, my wife and mother in law want to be notified whenever i look at cute girls.
Each time i look at a cute girl they should be notified and then they can take whatever action they want.
Typically, you would push or pull the data from the subject (that's me), to the observers (that's my wife and her mom).
Mo (that's me) contains an internal list of relatives that want to know what he's up to.
Anytime one of his relatives wants to check in on him, the add themselves to Mo's interal list.
If they're no longer interested, they can remove themselves for the internal list.
public Mo( IList< IObserver > concernedRelatives ) {
_concernedRelatives = concernedRelatives;
LookAtCuteGirl += delegate { OnLookedAtCuteGirl( ); };
}
public event EventHandler LookAtCuteGirl;
public void Add( IObserver observer ) {
_concernedRelatives.Add( observer );
}
public void Remove( IObserver observer ) {
_concernedRelatives.Remove( observer );
}
private IList< IObserver > _concernedRelatives;
private void OnLookedAtCuteGirl( ) {
foreach ( IObserver relative in _concernedRelatives ) {
relative.Update( );
}
}
Let's say my wife is concerned and wants to check up on me, here's how she would do it.
public MosWife( ISubject husband ) {
_husband = husband;
_husband.Add( this );
}
public void Update( ) {
Console.Out.WriteLine( "Why is my husband looking at cute girls?" );
}
private ISubject _husband;
She's decided to always add her self to my internal list to see what I'm doing.
If I should happen to check out a cute girl, she will be immediately notified.
Lucky for me, my wife is pretty laid back, and asks herself "Why is my husband looking at cute girls?"...
Hopefully, this helps to demonstrate the observer pattern.
I realize that it is rather contrived example, and the source could could be refactored. But hopefully it's clear.
For a better explanation, you should read...
Head First Design Patterns (Head First) by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra
Read more about this title...
P.S. My wife does not check up on me, she's awesome!
DesignPatterns.Observer.zip (4.01 KB)
"The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable.
Strategy lets the algorithm vary independently from clients that use it." - Head First Design Patterns
This means that at runtime you can switch the algorithm being used by a particular object.
In the example attached, there are a set of characters. Each characters has a weapon that they yield!
At runtime, you can switch the type of weapon that a particular character is using.
For instance if the character king was constructed to use a default weapon, at runtime you could switch out the weapon that the king uses when he is fighting.
This adheres to the open/closed principle,
where the king object is open for extension but closed for modification.
In the future if we wanted to add new weapons, we can add them without having to change the implementation of the king object.
This allows us to switch the type of weapon the king object is using at runtime!
1 King king = new King( );
2 king.Fight( );
3
4 king.Weapon = new Axe( );
5 king.Fight( );
6
7 king.Weapon = new BowAndArrow( );
8 king.Fight( );
For more information check out...
Head First Design Patterns (Head First) by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra
Read more about this title...
DesignPatterns.Strategy.zip (5.29 KB)