Is it a code smell that a repository has change events? - c#

I've not seen change events being used in repository pattern implementations, but I'd like to have my repository like this:
interface IEntityRepository
{
event EventHandler<EntityChangedEventArgs> EntityAdded;
event EventHandler<EntityChangedEventArgs> EntityRemoved;
IEnumerable<Entity> GetAll();
Entity GetById(int id);
}
This is largely because my entities can be added and removed from the outside only, and not by the client of IEntityRepository.
Am I thinking fundamentally wrong about the repository pattern by doing like this, or do I have a valid case?

I'd say yes, if you intend to use Fowler's actual Repository Pattern. That pattern is intended to be a mediator between business and data layers by exposing a collection-like interface. It was not intended to actually hold data. That said, if you merely want to create a collection that wraps an API and exposes events when things change, by all means do so. Sometimes you don't need to follow a predefined pattern.
If you want it to be a pattern, I'd say it looks more like an Object Pool or Observer pattern. Consider the case of IObservable using Reactive Extensions (Rx). It would allow you to react to the PInvoke layer, and force your responsibilities down the line. The code actually winds up being more effective than events. By using events, you have to maintain this repository, keep track of object lifetime, probably make this repository a singleton and give it some thread management. With Rx, you simply push an action on the observer's queue.
But in the end, use whatever feels most natural to you. Patterns are just suggestions, and don't always exist for every potential use case. This is one of those cases.

I have a similar issue where I need to publish events to an event store for CUD operations against a database (not concerned about Read operations). Rather than modify my repo I instead created a decorator and injected it (using SimpleInjector). That satisfies the Open/Closed principle and Single Responsibility, and actually it's provided a much cleaner way to handle that requirement.

Related

Replacing service layer with MediatR - is it worth to do it?

Do you think it might be reasonable to replace my service layer or service classes with MediatR? For example, my service classes look like this:
public interface IEntityService<TEntityDto> where TEntityDto : class, IDto
{
Task<TEntityDto> CreateAsync(TEntityDto entityDto);
Task<bool> DeleteAsync(int id);
Task<IEnumerable<TEntityDto>> GetAllAsync(SieveModel sieveModel);
Task<TEntityDto> GetByIdAsync(int id);
Task<TEntityDto> UpdateAsync(int id, TEntityDto entityDto);
}
I want to achieve some sort of modular design so other dynamically loaded modules
or plugins can write their own notification or command handlers for my main core application.
Currently, my application is not event-driven at all and there's no easy way for my dynamically loaded plugins to communicate.
I can either incorporate MediatR in my controllers removing service layer completely or use it with my service layer just publishing notifications so my plugins can handle them.
Currently, my logic is mostly CRUD but there's a lot of custom logic going on before creating, updating, deleting.
Possible replacement of my service would look like:
public class CommandHandler : IRequestHandler<CreateCommand, Response>, IRequestHandler<UpdateCommand, Response>, IRequestHandler<DeleteCommand, bool>
{
private readonly DbContext _dbContext;
public CommandHandler(DbContext dbContext)
{
_dbContext = dbContext;
}
public Task<Response> Handle(CreateCommand request, CancellationToken cancellationToken)
{
//...
}
public Task<Response> Handle(UpdateCommand request, CancellationToken cancellationToken)
{
//...
}
public Task<bool> Handle(DeleteCommand request, CancellationToken cancellationToken)
{
///...
}
}
Would it be something wrong to do?
Basically, I'm struggling what to choose for my logic flow:
Controller -> Service -> MediatR -> Notification handlers -> Repository
Controller -> MediatR -> Command handlers -> Repository
It seems like with MediatR I can't have a single model for Create, Update and Delete, so one way to re-use it I'd need to derive requests like:
public CreateRequest : MyDto, IRequest<MyDto> {}
public UpdateRequest : MyDto, IRequest<MyDto> {}
or embed it in my command like:
public CreateRequest : IRequest<MyDto>
{
MyDto MyDto { get; set; }
}
One advantage of MediatR is the ability to plug logic in and plug it out easily which seems like a nice fit for modular architecture but still, I'm a bit confused how to shape my architecture with it.
Update: I'm preserving the answer, but my position on this has changed somewhat as indicated in this blog post.
If you have a class, let's say an API controller, and it depends on
IRequestHandler<CreateCommand, Response>
What is the benefit of changing your class so that it depends on IMediator,
and instead of calling
return requestHandler.HandleRequest(request);
it calls
return mediator.Send(request);
The result is that instead of injecting the dependency we need, we inject a service locator which in turn resolves the dependency we need.
Quoting Mark Seeman's article,
In short, the problem with Service Locator is that it hides a class' dependencies, causing run-time errors instead of compile-time errors, as well as making the code more difficult to maintain because it becomes unclear when you would be introducing a breaking change.
It's not exactly the same as
var commandHandler = serviceLocator.Resolve<IRequestHandler<CreateCommand, Response>>();
return commandHandler.Handle(request);
because the mediator is limited to resolving command and query handlers, but it's close. It's still a single interface that provides access to lots of other ones.
It makes code harder to navigate
After we introduce IMediator, our class still indirectly depends on IRequestHandler<CreateCommand, Response>. The difference is that now we can't tell by looking at it. We can't navigate from the interface to its implementations. We might reason that we can still follow the dependencies if we know what to look for - that is, if we know the conventions of command handler interface names. But that's not nearly as helpful as a class actually declaring what it depends on.
Sure, we get the benefit of having interfaces wired up to concrete implementations without writing the code, but the savings are trivial and we'll likely lose whatever time we save because of the added (if minor) difficulty of navigating the code. And there are libraries which will register those dependencies for us anyway while still allowing us to inject abstraction we actually depend on.
It's a weird, skewed way of depending on abstractions
It's been suggested that using a mediator assists with implementing the decorator pattern. But again, we already gain that ability by depending on an abstraction. We can use one implementation of an interface or another that adds a decorator. The point of depending on abstractions is that we can change such implementation details without changing the abstraction.
To elaborate: The point of depending on ISomethingSpecific is that we can change or replace the implementation without modifying the classes that depend on it. But if we say, "I want to change the implementation of ISomethingSpecific (by adding a decorator), so to accomplish that I'm going to change the classes that depend on ISomethingSpecific, which were working just fine, and make them depend on some generic, all-purpose interface", then something has gone wrong. There are numerous other ways to add decorators without modifying parts of our code that don't need to change.
Yes, using IMediator promotes loose coupling. But we already accomplished that by using well-defined abstractions. Adding layer upon layer of indirection doesn't multiply that benefit. If you've got enough abstraction that it's easy to write unit tests, you've got enough.
Vague dependencies make it easier to violate the Single Responsibility Principle
Suppose you have a class for placing orders, and it depends on ICommandHandler<PlaceOrderCommand>. What happens if someone tries to sneak in something that doesn't belong there, like a command to update user data? They'll have to add a new dependency, ICommandHandler<ChangeUserAddressCommand>. What happens if they want to keep piling more stuff into that class, violating the SRP? They'll have to keep adding more dependencies. That doesn't prevent them from doing it, but at least it shines a light on what's happening.
On the other hand, what if you can add all sorts of random stuff into a class without adding more dependencies? The class depends on an abstraction that can do anything. It can place orders, update addresses, request sales history, whatever, and all without adding a single new dependency. That's the same problem you get if you inject an IoC container into a class where it doesn't belong. It's a single class or interface that can be used to request all sorts of dependencies. It's a service locator.
IMediator doesn't cause SRP violations, and its absence won't prevent them. But explicit, specific dependencies guide us away from such violations.
The Mediator Pattern
Curiously, using MediatR doesn't usually have anything to do with the mediator
pattern. The mediator pattern promotes loose coupling by having objects interact with a mediator rather than directly with each other. If we're already depending on an abstraction like an ICommandHandler then the tight coupling that the mediator pattern prevents doesn't exist in the first place.
The mediator pattern also encapsulates complex operations so that they appear simpler from the outside.
return mediator.Send(request);
is not simpler than
return requestHandler.HandleRequest(request);
The complexity of the two interactions is identical. Nothing is "mediated." Imagine that you're about to swipe your credit card at the grocery store, and then someone offers to simplify your complex interaction by leading you to another register where you do exactly the same thing.
What about CQRS?
A mediator is neutral when it comes to CQRS (unless we have two separate mediators, like ICommandMediator and IQueryMediator.) It seems counterproductive to separate our command handlers from our query handlers and then inject a single interface which in effect brings them back together and exposes all of our commands and queries in one place. At the very least it's hard to say that it helps us to keep them separate.
IMediator is used to invoke command and query handlers, but it has nothing to do with the extent to which they are segregated. If they were segregated before we added a mediator, they still are. If our query handler does something it shouldn't, the mediator will still happily invoke it.
I hope it doesn't sound like a mediator ran over my dog. But it's certainly not a silver bullet that sprinkles CQRS on our code or even necessarily improves our architecture.
We should ask, what are the benefits? What undesirable consequences could it have? Do I need that tool, or can I obtain the benefits I want without those consequences?
What I am asserting is that once we're already depending on abstractions, further steps to "hide" a class's dependencies usually add no value. They make it harder to read and understand, and erode our ability to detect and prevent other code smells.
Partly this was answered here: MediatR when and why I should use it? vs 2017 webapi
The biggest benefit of using MediaR(or MicroBus, or any other mediator implementation) is isolating and/or segregating your logic (one of the reasons its popular way to use CQRS) and a good foundation for implementing decorator pattern (so something like ASP.NET Core MVC filters). From MediatR 3.0 there's an inbuilt support for this (see Behaviours) (instead of using IoC decorators)
You can use the decorator pattern with services (classes like FooService) too. And you can use CQRS with services too (FooReadService, FooWriteService)
Other than that it's opinion-based, and use what you want to achieve your goal. The end result shouldn't make any difference except for code maintenance.
Additional reading:
Baking Round Shaped Apps with MediatR
(which compares custom mediator implementation with the one MediatR provides and porting process)
Is it good to handle multiple requests in a single handler?

What am I missing with the Respository Pattern? How do you use it in the real world?

Every example of the Repository Pattern I have seen deals with a very simple use case - one object type and the most basic CRUD operations. The Repository is then very often plugged straight into an MVC controller.
Real-world data access just isn't like this. Real-world data access scenarios can involve complex graphs of objects and some form of transactional wrapper. For example, suppose I want to save a new Order. This involves writing to the Order, OrderDetails, Invoice, User, History and ItemStock tables. All of this must be transacted, committed or rolled back. Normally I'd pass around something like an IDbTransaction and an IDbConnection and bundles the whole operation in a service layer.
Where does the Repository Pattern fit with this? Am I missing something (Unit Of Work perhaps)? Are there any more realistic examples of Repositories in use than the usual canned blog snippets?
Appreciate any light.
This is a very controversial subject but here is my catch from my own experience.
Repository works at the aggregate root. For example if an OrderItem is always retrieved as part of Order and does not have a life of its own outside order, then it will be loaded by the OrderRepository, otherwise it will have its own repository.
UnitOfWork is an important concept. Let's say OrderItem is an aggregate root and has its own repository. So at the time of creating an order, OrderManager will create a UnitOfWork of work in a using block, initialise OrderItemRepository and OrderRepository and then commit.
UPDATE
Yes, exactly. Imagine - in our case order - an order is being inserted. This needs to be in control of the transaction and enter order and order items separately inside the same transaction. This cannot be managed at the repository level. This is the sole reason for existence of UnitOfWork concept which is passed to the repository so that it does not own or initialise it. UnitOfWork usually is created at the business layer.
O/R-Mappers like Hibernate basically implement the Repository pattern for object graphs while fully supporting transactions. It's often a leaky abstraction, but it certainly can be made to work in complex real-world scenarios.
If you need a good full blown, widely used expample of the repository pattern look at Cocoa's Core Data I realize it is not in the realm of programming languages that you note. But note that it is NOT an O/R mapper. It is a complete abstraction of an object store. No Sql statements to execute, and while you may pick the format of the external storage that is used, you never interact with it directly.
I like to think of a repository as another layer of abstraction. You should only add layers of abstraction when the cost of their implementation is less than the cost of NOT doing the implementation (code maintenance, support, enhancements, etc).
Remember that the purpose of the repository pattern is to separate the logic that retrieves the data (CRUD) and maps it to the entity model from the business logic that acts on the model. What this often ends up doing/looking like in the real world is some form of business entities, that abstract the underlying physical data model.
As far as your transaction question, yes, this relates more to the Unit of Work pattern. Since you mentioned services, I would encourage you to NOT pass around your connection to your various data access classes/methods, but to instead allow WCF to manage the transaction for you using auto enlistment. Here is an extract of Juval Lowy's WCF book (highly recommended) that explains the how and why of this method of transaction management.
So to answer your question, the repository pattern fits in as a way to abstract the physical data model and to separate the CRUD/mapping from the business logic.

Resolving a call-chain anti-pattern

I've begun to notice something of an anti-pattern in my ASP.NET development. It bothers me because it feels like the right thing to do to maintain good design, but at the same time it smells wrong.
The problem is this: we have a multi-layered application, the bottom layer is a class handling calls to a service that provides us with data. Above that is a layer of classes that possible transform, manipulate, and check the data. Above that are the ASP.NET pages.
In many cases, the methods from the the service layer don't need any changes before going on the view, so the model is just a straight pass through, like:
public List<IData> GetData(int id, string filter, bool check)
{
return DataService.GetData(id, filter, check);
}
It's not wrong, nor necessarily awful to work on, but it creates an odd kind of copy/paste dependency. I'm also working on the underlying service, and it also replicates this patter a lot, and there are interfaces throughout. So what happens is, "I need to add int someotherID to GetData" So I add it to the model, the service caller, the service itself, and the interfaces. It doesn't help that GetData is actually representative of several methods that all use the same signature but return different information. The interfaces help a bit with that repetition, but it still crops up here and there.
Is there a name for this anti-pattern? Is there a fix, or is a major change to the architecture the only real way? It sounds like I need to flatten my object model, but sometimes the data layer is doing transformations so it has value. I also like keeping my code separated between "calls an outside service" and "supplies page data."
I would suggest you use the query object pattern to resolve this. Basically, your service could have a signature like:
IEnumerable<IData> GetData(IQuery<IData> query);
Inside the IQuery interface, you could have a method that takes a unit of work as input, for example a transaction context or something like ISession if you are using an ORM such as NHibernate and returns a list of IData objects.
public interface IQuery<T>
{
IEnumerable<T> DoQuery(IUnitOfWork unitOfWork);
}
This way, you can create strongly typed query objects that match your requirements, and have a clean interface for your services. This article from Ayende makes good reading about the subject.
Sounds to me like you need another interface, so that the method becomes something like:
public List<IData> GetData(IDataRequest request)
You're delegating to another layer, and it's not necessarily a bad thing at all.
You could add some other logic here or in another method down the line, that belongs only in this layer, or swap out to having the layer delegated-to with another implementation, so it certainly could be perfectly good use of the layers in question.
You may have too many layers, but I wouldn't say so just from seeing this, more from not seeing anything else.
From what you've described it simply sounds like you have encountered one of the 'trade-offs' of abstraction in your application.
Consider the case where those 'call-chains' no longer 'pass-thru' the data but require some tranformation. It might not be needed now and certainly the case can be made for YAGNI.
However, in this case it doesn't seem like too much tech debt to handle with the positive side effect of being able to easily introduce changes to the data between layers.
I use this pattern as well. However I used it for the purpose of de-coupling my domain model objects from my data objects.
In my case, instead of "passing through" the object coming from the data layer as you do in your example, I "map" it to another object that lives in my domain layer. I use AutoMapper to take out the pain of manually doing it.
In most cases my domain object looks exactly the same as my data object that it originated from. However there are times when I need to flatten information coming from my data object... or I may not be interested in everything that is in my data object etc.. I map the data object to a customized domain object that only holds the fields my domain layer is interested in.
Also this has the side effect that when I decide to re factor or change my data-layer for something else, It does not have to affect my domain objects since they are de-coupled using the mapping technique.
Here is a description of auto-mapper, which is sort of what this design pattern tries to achieve I think:
AutoMapper is geared towards model projection scenarios to flatten complex object models to DTOs and other simple objects, whose design is better suited for serialization, communication, messaging, or simply an anti-corruption layer between the domain and application layer
Actually, the way you have chosen to go, is the reason of having what you have (I am not saying it is bad).
First, let me say your approach is quite normal.
Now, let me go thought your layers:
Your service - provides somewhat kind of strongly-typed access model. What that means is it has some types of arguments, used them in some special types of methods which return again some special type of results.
Your service-access-layer - also provides the same kind of model. So that it takes special kinds of arguments for special kinds of methods, returning special kinds of results.
etc...
In order not to confuse, here is what I call special kind:
public UserEntity GetUserByID(int userEntityID);
In this example you need to pass exactly the Int, while calling exactly the GetUserByID and it will return exactly the UserEntity object.
Now another kind of approach:
Remember how SqlDataReader works? not very strongly-typed, right?
What you call here for, in my opinion, is that you are missing some not-strongly typed layer.
For that to happen: you need to switch from strongly-typed to non-strongly typed somewhere in your layers.
Example:
public Entity SelectByID(IEntityID id);
public Entity SelectAll();
So, if you had something like this instead of the service access layer, then you could call it for whichever arguments you wanted.
But, that is almost creating an ORM of your own, so I would not think this is the best way to go.
It's essential to define what kind of responsibility goes to which layer, and place such logic only in the layer it belongs to.
It's absolutely normal to just pass through, if you don't have to add any logic in particular method. At some time you might need to do so, and abstraction layer will pay off at that point.
It's even better to have parallel hierarchies, not just passing the underlying layer's objects up, so each layer uses it's own class hierarchy, and you can employ something like AutoMapper in case you feel there's no much difference in the hierarches. This gives you flexibility, and you can always replace automapping with custom mapping code in particular methods/classes, in case hierarchies do not match anymore.
If you many methods with almost the same signature, then you should think of Query Specification pattern.
IData GetData(IQuery<IData> query)
Then, in presentation layer you can implement a databinder for your custom query specification objects, where a single aspnet handler could implement creation of specific query objects, and passing them to a single service method, which will pass it to a single repository method, where it can be dispatched according to a specific query class, possibly with a Visitor pattern.
IQuery<IData> BindRequest(IHttpRequest request)
With this to Automapping and Query Specification pattern, you can reduce duplication to a minimum.

Is it OK to use manager classes as Singletons?

For each concrete class I have a Manager class. This class has methods like GetAll(), GetById(), Save, etc.
I've made these manager classes a Singleton because I always need one instance, and I have the ability to cache results. For example, when I call GetAll() and the next time I need this method again, the manager don't have to go to the database, it can return the cached results.
Is this a good approach? Or is there a better alternative way?
What you call manager classes are really "repositories"
Repositories should only work at an aggregate root level, not one repository per class. E.g. if I have an Order class which has a collection of OrderItem, then an Order repository would exist that would have Get/GetAll methods - as the Order is the agg root in this case.
All repository classes would usually be singleton classes, where you can usually enforce this easily via an IOC container.
Overall, I would say your approach of one "repository" per entity is bad - stick to one repository per aggregate root instead.
Why not include them as part of the concrete class but static? Saves the need for two seperate classes.
It sounds like you are close to implementing the Repository pattern, but not quite all the way there. I'd suggest looking into it. I wouldn't make them Singletons -- it makes it too hard to mock them out for your unit tests so you end up adding back doors to defeat the Singleton for testing. A cache makes a nice Singleton object, but why not simply share the cache this way instead of multiplying Singletons?
For testing/mocking purposes, I would advise against using a Manager/Repository Singleton.
If you do want to cache results, then I would suggest delegating to a dedicated Cache class. Any static magic can be contained within the Cache class and your Manager/Repository's semantics can be kept clean.
From a Single Responsibility Principle point of view, I should be able to understand how a Manager/Repository works without having to understand your caching scheme.

Patterns: Local Singleton vs. Global Singleton?

There is a pattern that I use from time to time, but I'm not quite sure what it is called. I was hoping that the SO community could help me out.
The pattern is pretty simple, and consists of two parts:
A factory method that creates objects based on the arguments passed in.
Objects created by the factory.
So far this is just a standard "factory" pattern.
The issue that I'm asking about, however, is that the parent in this case maintains a set of references to every child object that it ever creates, held within a dictionary. These references can sometimes be strong references and sometimes weak references, but it can always reference any object that it has ever created.
When receiving a request for a "new" object, the parent first searches the dictionary to see if an object with the required arguments already exists. If it does, it returns that object, if not, it returns a new object and also stores a reference to the new object within the dictionary.
This pattern prevents having duplicative objects representing the same underlying "thing". This is useful where the created objects are relatively expensive. It can also be useful where these objects perform event handling or messaging - having one object per item being represented can prevent multiple messages/events for a single underlying source.
There are probably other reasons to use this pattern, but this is where I've found this useful.
My question is: what to call this?
In a sense, each object is a singleton, at least with respect to the data it contains. Each is unique. But there are multiple instances of this class, however, so it's not at all a true singleton.
In my own personal terminology, I tend to call the parent class a "global singleton". I then call the created objects "local singletons". I sometimes also say that the created objects have "reference equality", meaning that if two variables reference the same data (the same underlying item) then the reference they each hold must be to the same exact object, hence "reference equality".
But these are my own invented terms, and I am not sure that they are good ones.
Is there standard terminology for this concept? And if not, could some naming suggestions be made?
Thanks in advance...
Update #1:
In Mark Seemans' reply, below, he gives the opinion that "The structure you describe is essentially a DI Container used as a Static Service Locator (which I consider an anti-pattern)."
While I agree that there are some similarities, and Mark's article is truly excellent, I think that this Dependency Injection Container / Static Service Locator pattern is actually a narrower implementation of the general pattern that I am describing.
In the pattern described in the article, the service (the 'Locator' class) is static, and therefore requires injection to have variability in its functionality. In the pattern I am describing, the service class need not be static at all. One could provide a static wrapper, if one wants, but being a static class is not at all required, and without a static class, dependency injection is not needed (and, in my case, not used).
In my case the 'Service' is either an interface or an abstract class, but I don't think that 'Service' and 'Client' classes are even required to be defined for the pattern I am describing. It is convenient to do so, but if all the code is internal, the Server class could simply be a 'Parent' class that controls the creation of all children via a factory method and keeps weak (or possibly strong) references to all of its children. No injection, nothing static, and not even a requirement to have defined interfaces or abstract classes.
So my pattern is really not a 'Static Service Locator' and neither is it a 'Dependency Injection Container'.
I think the pattern I'm describing is much more broad than that. So the question remains: can anyone identify the name for this approach? If not, then any ideas for what to call this are welcome!
Update #2:
Ok, it looks like Gabriel Ščerbák got it with the GoF "Flyweight" design pattern. Here are some articles on it:
Flyweight pattern (Wikipedia)
Flyweight design pattern (dofactory.com)
Flyweight Design Pattern (sourcemaking.com)
A 'flyweight factory' (server) and 'flyweight objects' (client) approach using interfaces or abstract classes is well explained in the dofactory.com article an is exactly what I was trying to explain here.
The Java example given in the Wikipedia article is the approach I take when implementing this approach internally.
The Flyweight pattern also seems to be very similar to the concept of hash consing and the Multiton pattern.
Slightly more distantly related would be an object pool, which differs in that it would tend to pre-create and/or hold on to created objects even beyond their usage to avoid the creation & setup time.
Thanks all very much, and thanks especially to Gabriel.
However, if anyone has any thoughts on what to call these child objects, I'm open to suggestions. "Internally-Mapped children"? "Recyclable objects"? All suggestions are welcome!
Update #3:
This is in reply to TrueWill, who wrote:
The reason this is an anti-pattern is because you are not using DI. Any class that consumes the Singleton factory (aka service locator) is tightly coupled to the factory's implementation. As with the new keyword, the consumer class's dependencies on the services provided by the factory are not explicit (cannot be determined from the public interface). The pain comes in when you try to unit test consumer classes in isolation and need to mock/fake/stub service implementations. Another pain point is if you need multiple caches (say one per session or thread)
Ok, so Mark, below, said that I was using DI/IoC. Mark called this an anti-pattern.
TrueWill agreed with Mark's assessment that I was using DI/IoC in his comment within Mark's reply: "A big +1. I was thinking the same thing - the OP rolled his own DI/IoC Container."
But in his comment here, TrueWill states that I am not using DI and it is for this reason that it is an anti-pattern.
This would seem to mean that this is an anti-pattern whether using DI or not...
I think there is some confusion going on, for which I should apologize. For starters, my question begins by talking about using a singleton. This alone is an anti-pattern. This succeeded in confusing the issue with respect to the pattern I am trying to achieve by implying a false requirement. A singleton parent is not required, so I apologize for that implication.
See my "Update #1" section, above, for a clarification. See also the "Update #2" section discussing the Flyweight pattern that represents the pattern that I was trying to describe.
Now, the Flyweight pattern might be an anti-pattern. I don't think that it is, but that could be discussed. But, Mark and TrueWill, I promise you that in no way am I using DI/IoC, honest, nor was I trying to imply that DI/IoC is a requirement for this pattern.
Really sorry for any confusion.
It looks like classic Flyweight design pattern from the GoF book. It does not cover the singleton factory with hash map, but generally covers saving on space and performance by reusing already created object, which is referenced by many other objects. Check out this pattern.
The objects themselves aren't following the singleton pattern, so maybe referring to the fetched objects as singleton can be confusing.
What about a Recycling Factory? :]
The structure you describe is essentially a DI Container used as a Static Service Locator (which I consider an anti-pattern).
Each of the services created by this Service Locator has a so-called Singleton lifetime. Most DI Containers support this as among several available lifetimes.

Categories