Wednesday, October 24, 2007

My Example of Factory Method Pattern

I found rather useful reading a "Design Patterns" and found some examples of those patterns in programs I've written or read. And some days ago I've used one of the patterns - Factory Method.

What was the case? I've wrote two types of collections for C#: Vector (casual array) and LList (Linked List). They have the same interface ISequence and sane base abstract class SequenceBase which implements most of operations leaving virtual only basic operations, such as Insert, Remove, etc. And I wanted to have tests for all methods for both implementations. I'm using NUnit, and I didn't wanted to have two test classes with identical content, in except of operation new. So what I've made:
  1. Wrote an abstract class with all test cases (e.g. SequenceTester). All test methods have their Test tag.
  2. Class defines an abstract method Instance, which returns an object of tested interface, ISequence in my case.
  3. In all test methods I use Instance instead of operation new.
  4. For each tested class I define a test class derived from SequenceTester. In have to implement only Instance method that returns an instance of tested class and tests for an implementation of interface is ready!
The only thing I need to care is to add a test class for each implementation. Rather easy? ;) And moreover generation of concrete test classes could be delegated to special tool run before test process and building of tests.

Whats is good, as I think, is that such an approach could be used to test all implementations of each interface. Write tests for interface in abstract class, write tool to search implementations and generate required test classes and you can be sure that this interface work well in all cases, or in other case you get a pointer(s) to error(s).

I think I'll try to use this approach in my practice and write such a tool to make concrete classes for tests of interface implementations.

Off-topic: While writing this post I again faced the question: why implement array and linked list with same interface? The difference in the way they work make some operations unsuitable for one type while be good for other, so why include these operation in common interface? I think it's the question worth its own article, so I'll explore this question in future.

No comments: