Adapter Design Pattern

This design pattern is pretty easy to use and understand, so this article is going to be short. First of all, why do we need it at all? Well, the main reason is the following – there are some classes that might implement useful algorithms, but we expect a bit different output out of them. For instance:
1) Legacy shape uses top left coordinates, and then height and width for rectangle. We would like to use top left and bottom left coordinates knowing we are talking about rectangle initially.
2) We have old customer authentication interface which expects different type of Customer class that we use.

In other words, there are lots of reasons why Adapter can and should be used. I will give a sketch of real-world example for the customer authentication. Let us say that old authentication API uses the following class for Customer:

public class APICustomer {
    public Email { get; set; }
    public Password { get; set; }
}

And we use the following class:

public class Customer {
    public UserName { get; set; }
    public Password { get; set; }
}

And now we need some adapter that adapts our Customer to APICustomer. We can implement it in the following way:

public class CustomerAdapter {
    public static APICustomer Adapt(Customer c) {
        // Given the circumstances that all users use example.com as email domain.
        // In the Gmail users' database it might actually be so. However, in a more real-world adoption of APICustomer would be much more difficult or even impossible.
        // Still, this is not a bad example to illustrate use of it.
        return new APICustomer { Email = c.UserName + "@example.com", Password = c.Password };
    }
}

And this is it. Basically, I have introduced a pretty simple class that converts object of Customer to APICustomer object. In other words, it means that Adapter does not have any sort of strict obligations regarding use of it, so Adapter might be almost everything that you use everyday in your programming life. Just think about it.

Singleton Design Pattern

There are some things that people always talk about, they think they know everything about it. But this is actually an indication that something is wrong here. Why? Well, there are lots of ways (wrong ones) to implement Singleton that it raises a question. Is it really useful? How?

I am not going to talk here about if Singleton is a good pattern or not, or how to implement it. I like talking about more difficult ones. And Singleton is really simple. It just ensures that item will get initialized once and only once. How is it done, it depends on the programming language, compiler, even the context (clearly, it is impossible to have Singleton design pattern implementation on two separate devices :)), and lots of other things that can come by.

So, what is the problem actually that Singleton solves? It appears that no problem is being solved. Mostly, more problems ARE INTRODUCED than solved in this way. If you like, you can take a look into this example: https://sourcemaking.com/design_patterns/singleton . Example here is some government or government institution. It looks really “developer friendly” (oh, the irony). However, it is not really a Singleton, since governments can change and they change every term, so how unique is this example… Well, I am unable to comprehend this.

Another popular example for Singleton is logging something for some reason. But why people choose to use Singleton for loggers? I am not sure about that, either. Maybe it is the influence of bad examples for usage of Singleton. Clearly, you can create the logger in the following way (if not, please tell me why):

  1. Introduce ILogger (some interface required for logging).
  2. Introduce Logger that implements ILogger.
  3. Instantiate Logger during app startup or add it to IoC Container.
  4. Add ILogger as dependency everywhere it needs to be used.

However, it becomes a bit of problem when IoC Container is not used (or can not be used just right now), and there are lots of classes that needs logging. So, some people just introduce Logger as singleton. And yes, then it logs everything you want, but this introduces huge code smell that is hard to resolve. Also, it is not unit testable or in order to unit test it you are required to add some magical stuff that other developer who looks just into your unit tests might not know anything about it. And sometimes you might really want to test what actually gets logged. Thus, from my point of view Singleton mostly is used by people who are not tend to refactor their architecture of their software, and they try to use most short-sighted way of thinking. This is when Singleton gets used.

Still, Singleton CAN be useful sometimes. When? In IoC Containers it can be useful. For instance, most of the IoC Containers instantiate objects that are memory location agnostic (and it should be), but sometimes building the infrastructure for the whole app we would like a couple of classes to be non-memory agnostic. For instance, maybe we would like to log all of the activity to RAM first, and then initiate some background thread that would flush all of this data to some storage to make it more efficient. In order to be able to conserve some memory, we might actually want to have a Singleton. However, most of the modern IoC Containers support ability to make class instance as Singleton (e.g. Autofac in the C#), so even in this case you would not need to implement Singleton, since it is done for you already by other developers who suffered all of the implementation pain for you. So, why would you want to suffer again if your goal is to develop some industry level app instead of learning? I think that development of commercial apps and learning should not be coupled too much.

In other words, Singleton has its’ own uses, but all of the modern frameworks take care of that for you mostly, so actually there is no need to implement Singleton for you (unless you are going to implement some framework which is the case pretty rarely today). It is simple and really addictive pattern to use, but if you think you want to use Singleton, you should think about refactoring your code instead, since in this way you are making your code even worse than it is right now.

Object Pool Design Pattern

Object Pool Design Pattern is pretty simple one. However, even here tutorials might fail. Let us take a look into a couple of examples:

  1. https://sourcemaking.com/design_patterns/object_pool
  2. https://www.geeksforgeeks.org/object-pool-design-pattern/

Both of these examples talk about performance like it should be the most important thing for the Object Pool while performance here is really important, but it is taken into consideration from a bit different angle. For instance, let us take a look into examples that Object Pool might actually be useful: Parallelization of jobs being performed. This is probably one and only class where Object Pool is actually useful. You take some tasks, you parallelize them across different threads, and you use Object Pool as a Factory or a provider for these objects. Creation and providing of these objects have nothing to do with performance. If you need something to do with performance in the object level, use Prototype for that, not an Object Pool.

In other words, it is correct to say that Object Pool might give some performance benefits. But it is retrieved through the pattern itself instead of through object creation. And finally, we should treat design patterns as an abstract way of designing our algorithms and systems. So, what actually does Object Pool give us? Well, it gives as a pretty centralized and easy to use API to get the objects we might want to get.

Another problem with the Object Pool is the example itself in the first tutorial. Why do we need always to compare design patterns with something which is completely unrelated to the Software Development? So we would be able to pretend that we understand what is this design pattern, yes? Why not trying to ACTUALLY understand and USE it instead of PRETEND? It would be much better for everyone.

So, let us take a look into the following code:

// First, we define the interface for generic Object Pool.
public interface IObjectPool<T>
{
    T Acquire();
 
    void Release(T node);
 
    void SetMaximumPoolSize(int size);
}
 
// Then, we define some Resource. Let us say it will be some node analysing website URL.
public interface IWebsiteURLAnalysisNode
{
    string Analyse(string url);
}
 
// And finally, we have the Object Pool itself:
public class AnalysisNodePool : IObjectPool<IWebsiteURLAnalysisNode>
{
    private static Semaphore _semaphore = new Semaphore(3, 3);
    private static AnalysisNodePool _instance = new AnalysisNodePool();
    private readonly Stack<IWebsiteURLAnalysisNode> _nodes = new Stack<IWebsiteURLAnalysisNode>();
    private readonly IWebsiteURLAnalysisNodeCreator _creator; // This would be initialized somehow, but for simplicity I am not doing this here.
 
    private AnalysisNodePool()
    {
    }
 
    // Would use some IoC Container (like Autofac), but for simplicity this is not bad. Just make sure not to include this into your real projects. Statics are not good if they can be replaced with non-statics.
 
    static AnalysisNodePool GetInstance()
    {
        return _instance;
    }
 
    public IWebsiteURLAnalysisNode Acquire()
    {
        _semaphore.WaitOne();
 
        if (_nodes.Count == 0)
        {
            return _creator.Create();
        }
 
        return _nodes.Pop();
    }
 
    public void Release(IWebsiteURLAnalysisNode node)
    {
        _nodes.Push(node);
 
        _semaphore.Release();
    }
 
    public void SetMaximumPoolSize(int size)
    {
        _semaphore = new Semaphore(size, size);
    }
}

As you can see, example is pretty real, since semaphore is used (to ensure maximum number of resources would get used at the same time). So, this is the example of how to actually use Object Pool design pattern. But why use it for crawler? Well, the reason here is that we know pretty well that number of sockets can be limited. Theoretically, it can be unlimited, but this would give no real benefit, thus adding abstraction to limit number of them in an easy manner is pretty nice way of thinking here. Still, not sure if this is very necessary for simple website crawler projects.

In other words, if you know that you have limited amount of resources that need to be shared among some other classes, then Object Pool Design pattern can be used. The main reason to use Object Pool is to provide some API of acquiring objects representing limited amount of resources, not efficiency as some examples like to say. Efficiency gains might be here, but this is not the reason.

Factory Method Design Pattern

Actually, this is quite simple pattern. However, there are so many inappropriate examples (toy code, non-understandable and useless ones) and even more cryptic explanations that you can easily get confused and think what is the point in using this design pattern? It contains lots of awful examples where using Factory Method does not show its’ possible and practical purpose in no way. For example, let us take a look into a Book Factory! https://sourcemaking.com/design_patterns/factory_method/php/1

Seriously, am I supposed to use this for some Books? Why? What is so special about the book that the book having different title, publisher or any other attribute that can be represented in a primitive data types, i.e. so special that I am supposed to create a Book Factory? Builder for books? Maybe, since there might be massive amount of attributes I would like to set comfortably and abstract setting them. Using Prototype for the Book itself? For the Book itself no way, but if the source is some remote data source, then Prototype can be useful, so Book can really implement ICloneable. But Factory Method for the Book? Maybe there are some ways, but I tend to simplify most difficult processes in most simplistic way possible, so it would be easier to manage them later. Thus, I think Book should not be used as an example for Factory Method. It is just too misleading from actual purpose of this awesome design pattern.

In order to find a proper example for usage of Factory Method, first we should take a couple of points why it is used. Some of the points mentioned in various resources are the following:

  1. Abstraction of new object creation. Yes, this is correct, and it is extremely useful in the IoC Containers where Factory Method is used in this way. However, IoC Containers for this article is a bit too complex example to get real understanding of Factory Method, thus I will leave it out here.
  2. Some say that way how objects are instantiated (created newly in memory or returned from some cache) should not matter for the client. Well, I am not so sure. Even if client will know that new object gets put somewhere and somehow in the memory, I think no client will know exactly the internals of that. If the “new” operator would be really harmful as some people tend to say, then no Object Oriented Programming Language would have operator “new”. As a client, I might want to write code in a way that does not restrict me in any ways. Or at least I would like to have intuitive enough API to write the code. In any case, it is wrong to assume what other developers want from me as an API developer. I can only assume the most standard needs: intuitive and easy to use API, understandable documentation, practical and useful examples (not some too primitive examples like “Hello, World”). However, I really agree that “new” should be avoided if it is possible to get the result without in a more elegant way. But still it should be used somewhere. We just should find proper place for it, not avoid it.
  3. Abstract logic that would come out of direct composition of two actual objects. And this can be quite a real reason to use Factory Method. For instance, you might have some main class for doing something, then you might have another class which also does something where another class has something that does something, and so on. Providing an interface as a proper closure for such type of logic really helps, since it becomes unit testable.
  4. Another thing that is suggested is to use some static class for the main factory. Actually, it is one of the antipatterns that you can think of. If possible, you should avoid this at any costs. What if I intend to use the factory in some model class that creates different objects based on the input provided? With static classes, I would be unable to write unit tests in isolated manner.
  5. And so many more explanations.

There are so many explanations due to the following reasons:

  1. Some people confuse Factory Method with Factory. They are different. Factory is used to create objects whose classes resolve to the same top level definition (parent/grandparent) based on some input parameters. Some even say it is not a pattern, and just a programming technique. Well, we have in this world lots of grammar purifiers. Probably, there is no exception in the developers’ world. So, what actually Factory is? Yes, it is a software development technique. And what a Design Pattern is? Also, it is some sort of software development technique. Thus, simple Factory is also a proper design pattern, since it is a common way to solve the problem specified. Factory is just not the part of GoG patterns. Maybe because it is so obvious and simple that any developer would think about it out of intuition. Still, I think Design Patterns are much more than GoG classics in today’s world.
  2. Some even confuse Factory Method with Abstract Factory. It is a rare case, but I have seen this in code working on the project a couple of years ago.
  3. And most probably just have not enough knowledge in Mathematics, verbal communication is not good enough regarding extremely important things. In other words, they do not actually understand what the Factory Method is, and just pretend to understand. However, they use it all the time. Which is strange, but it happens so.

Thus, I am going to explain this pattern once and for all not to make any confusions regarding it. It is pretty sad to see so many toy examples that are never going to help. So, what example for the Factory Method can be useful? Document factory method INTEGRATED into some document storage medium might be useful example where there is IDocument interface that gives as FileName (e.g. example.json) and its’ JSON representation. For instance, we might have some byte stream and we want to be able to store it in different document storage formats: DOC, DOCX, PDF, HTML, and so on. Currently, we have no idea how to convert that byte[] stream to PDF, DOC, DOCX, and so on. Maybe we do not even know what to expect in that byte[] stream. So, let us create a base class for storage medium based on these unknowns:

// Product participant.
public interface IDocument
{
    string AsJSON { get; }
 
    string FileName { get; }
}
 
// This has not to be a factory or something. It is just a Creator participant, and that is it.
public abstract class DocumentStorageBase
{
    // This is the factory method we are going to use.
    // This is the main point of Factory Method. You can not know exactly what type of document will get created here, but
    // you know that there will be some fixed interface (a.k.a. Product participant).
    protected abstract IDocument Create(byte[] content);
 
    // Just a simple storage method. We have the interface, the data in it, thus we know how to save it in some file.
    public void Store(byte[] content)
    {
        var document = Create(content);
 
        var fileName = document.FileName;
        var json = document.AsJSON;
 
        // Store the document somewhere.
        // Not implementing here, since I want to show the use for pattern, not implementation. You can think of any implementation you like.
    }
}

Then, let us say we know we will have to be able to store PDF documents. So, we introduce two new classes.

// Concrete Product participant.
public class PDFDocument : IDocument
{
    public string AsJSON { get; set; }
 
    public string FileName { get; set; }
}
 
// Concrete Creator Participant.
public class PDFDocumentStorage : DocumentStorageBase
{
    protected override IDocument Create(byte[] content)
    {
        // Some difficult conversion logic that is able to get PDFDocument object from byte[].
        // This class would definitely include some dependency injection.
        return new PDFDocument();
    }
}

And that is it. This is everything about Factory Method. We covered all of the participants, and I have shown a pretty useful example which can really get benefits from the Factory Method. As you can see, Factory Method is extremely powerful pattern, and can be used in such cases where you know just a resulting interface/base class (a.k.a. Product participant), and you want someone else to create Concrete Product participants (i.e. they are created by Concrete Creator participants). And Creator itself is just an abstract class exposing an API method to override Factory Method which is used to create Concrete Product participants.

To sum up everything, Factory Method can be defined in the following way:

  1. It is a Creational Pattern allowing us to defer responsibility of object creation to the child-level through parent-level abstract method definition.
  2. There are four participants: Product (base interface both Client and API developer agree on), Creator (base class which introduced Product creation Factory Method which is abstract and should be implemented by child classes), Concrete Creator (implements the Factory method), Concrete Product (instance of Product interface created by Concrete Creator).
  3. It is useful when you know nothing about concrete products that might be instantiated, but you have a pretty good idea of the interfaces, and you exactly know what needs to be done. In other words, you know WHAT, but you do not know HOW, yet. Or you just want to leave HOW part for later.

Finally, there are some pretty nice explanations regarding Factory Method, too. At least the following one is the single one I was able to find where at least explanation is nice: https://exceptionnotfound.net/the-daily-design-pattern-factory-method/ . Explanation is short, clear, and from this you can really get the idea HOW to use Factory Method. But not sure about WHY. Example is original maybe, but not very useful from the real-world perspective, since it does not show WHY Factory Method should be used. I can code all of the sandwiches without any of the Design Patterns, and I would not lose anything. However, I would lose massive amount of nerves, time, and lots of other stuff if I would try to code smart Website Crawler by trying to include all of the rules in a single class. Or to create God of Documents (a.k.a. God Object that is able to create and store PDF, DOC, DOCX, HTML, XML, and so many more document formats in a single class). By using Factory Method, I can concentrate on the things I know right now, and do not bother that I might not know right now something, since I will always be able to extend the class without violation of SOLID (especially Single Responsibility and Open/Closed principles), and do not worry too much of some unknowns. That is why Factory Method can be used. But for sandwiches, books, colors, shapes… These examples are inappropriate. No one codes different classes for books if title is different. And if one does, then software design in that project should be very messy.

Abstract Factory Design Pattern

How this pattern is described? Well, according to the following sources, description is somehow vague:

  1. https://sourcemaking.com/design_patterns/abstract_factory : “…lots of #ifdef case statements with options for all currently supported platforms begin to procreate like rabbits throughout the code”. So, is this pattern about rabbits?
  2. https://www.tutorialspoint.com/design_pattern/abstract_factory_pattern.htm : “super-factory”, “factory of factories”.
  3. https://www.geeksforgeeks.org/abstract-factory-pattern/ : Some creation pattern that is another layer of abstraction over factory pattern.

Does this make anything clear? Of course, NOT. Such explanations are vague, wrong and unclear why Abstract Factory is needed, since it raises simple question that no one asks? Why should I use Abstract Factory at all? Maybe I can use just a Factory? Maybe I can use just “new” and that would be it? In other words, I will never use some design pattern unless it is logically and explicitly proven useful or even unavoidable in order to solve some problem. But it looks like that people use design patterns just to look cool and knowing some stuff about patterns. This way of using some technique is extremely bad programming example which causes lots of over-engineering in the systems which is the same bad thing as under-engineering.

So, I will try to remove the shadows around this pattern. First of all, let us take a look into the structure of this pattern. The structure is pretty simple actually. First of all, we have some interface:

interface IFoo {
    void Bar();
}

Now we have lots of objects implementing interface IFoo which implements method “void Bar()” somehow differently. Why? Because they can. So, let us say we have the following implementations: Foo1, Foo2, Foo3, …, FooN. After that, we have some factory that can produce all of the foos.

interface IFooFactory {
    IFoo GetFoo(string fooType);
}

As you can see, I could have actually introduced concrete factory in advance. But instead, I have decided to introduce an interface for the factory. In this way, I am saying that we can have multiple of factories. Why? Because we do not know in advance if there will be a need for one or more factories. So, it is good to introduce an interface in case we will have to introduce something more. In other words, now we have just to introduce factories for the IFooFactory, and we already have our own Abstract Factory Design Pattern implementation. And that is everything about structure of the Abstract Factory.

In other words, it is really simple. You have just two interfaces you are working around:

interface IFactory {
    ISomeItem Create();
}
 
interface ISomeItem {
    // Contract regarding ISomeItem.
}

After that, you just implement either ISomeItem or IFactory. And that is everything you need to know about Abstract Factory. So, it is actually incorrect to say it is “factory of factories”, since you do not make any of the factories from the client point of view. For some weird reason, lots of tutorials include client as a reference, but why if it’s point of view is not taken into account at all? I am not so sure. Maybe people again pretend that they know what they do not actually at all.

So, then why is it still called as “factory of factories”. Well, it is a bit like that, but the factory itself is produced mostly at the startup of the application or something like that, i.e. there is mostly no point to have interface instantiating a factory (and this also violates SOLID, since complex logic is introduced for more paths than one) in some of the class. In some class, factory is needed at most and that is it. So, basically you would have the following code regarding this pattern:

std::string GetOperatingSystem() {
    #ifdef IS_MAC
    return "mac";
    #elif IS_WIN
    return "win";
    #endif
    return "";
}
 
int main() {
    // It is logical to assume that dialogs, some controls get built really differently on different operating systems due to massive
    // differences in their implementations.
    IViewProvider someNativeDialogProvider = ViewProviderFactory().Get(GetOperatingSystem());
 
    SomeViewClient client(someNativeDialogProvider);
    client.InitializeApp();
 
    return 0;
}
 
// Yes, it is more reasonable to be more abstract here detection of device itself and concentrate on the structure we want to layout for the user.
class SomeViewClient
{
public:
    SomeViewClient(IViewProvider& provider) : m_provider(provider) {}
 
    void InitializeApp()
    {
        m_provider.ListenForUserInput({ "first_name", "last_name" }, [this](const blah& input) {});
        m_provider.OpenMainDialog("My Awesome App", [this]
        {
            m_provider.ShowInputField("first_name", "Enter Your Name");
            m_provider.ShowInputField("last_name", "Enter Your Last Name");
            m_provider.ShowButton("Submit All Data");
        });
    }
 
private:
    IViewProvider& m_provider;
};

I think there Abstract Factory can be used, since buttons, input listeners, fields, dialogs will all be different across the platforms. So, what is the main point for the Abstract Factory? The main points are the following:

  1. Detect some input that you would like to leave out of the logic you implement. For instance, you would like on creation of data items on separate database, separate operating system. It would be not nice to have everything boiler-plated in a single place.
  2. When detecting that input, create the Factory interface that creates another Factory based on that input.
  3. Create all of the Factories you need.
  4. Each Factory should create family of objects that is relevant for the input you have extracted out of the system.