I noticed a pattern in my code. It applies to situations where things can be selected. It revolves around classes which I call (and in code often suffix with) Registry, Slot and Updater.
Registry
This class is pretty much a combination of what is known as the registry pattern: (“A well-known object that other objects can use to find common objects and services.”) and some filter methods.
These are supposed to be the list of all [Type]s. They always use a collection internally, but the methods they have is determined by what other classes want from them. That might be simple wrappers for the collection class or domain specific, named filter methods. Events – for example when an item is removed – are added pragmatically when needed.
public class ProductRegistry { private readonly List<Product> _products = new List<Product>(); public void Add(Product product) { _products.Add(Product product) } public List<Product> GetAllProductsOnSale() { // domain specific filtering... } }
Slot
Named “Slot” because it can hold an object. In most cases, an object being held here means it is the currently selected object. Contrary to Registry and Updaters, the code for this is always the same except for the type of what is being selected. I could turn this into a generic class, but I only came to think of that while writing this question – and it’s not like that would change how this pattern works.
public class ProductSlot { public event Action WhenProductHasBeenChanged; public Product Product{get; private set;} public void Set(Product product) { Product = product; if(WhenProductHasBeenChanged!=null) WhenProductHasBeenChanged(); } }
Updaters
These update the registry and slot. How they achieve that varies wildly, so example code wouldn’t make sense here.
However, to give an example of what they do, a ProductUpdater
might supervise the process of downloading a string from a web address, parsing it into Products
and then add those to the ProductRegistry
.
One thing I did repeatedly was registering an Updater to the change event of a slot for a different thing. For example, a ContractSlotUpdater
listens to changes in a CustomerSlot
, so it can update the ContractSlot
with the Contract
which corresponds to the new Customer
.
Additional notes
I added the C# tag because that is the language – and thus the language features – that I am currently using. I see no problem transferring this concept to other languages as long as they have the necessary features.
The question
If this is not a good thing to do, please tell me why.
Otherwise, I would like to know what to call it.