Search code examples
design-patternsfactory-patternabstract-factory

Can Abstract Factory and Factory Method be used together?


Before dismissing this question, I am in fact asking this as a practical question, not to spark a conversation. Here is my scenario

I have read in many instances that the Abstract Factory is an implementation one step further then the Factory Method, and I can see in many situations why this is true. I also have a fairly good understanding of the difference between these two, but I have recently ran into a scenario where I have been directed to use both of these together.

It has been racking my brain how to do this, and I am still unsure if it is recommended as a good practice or not.

Do you, or can you point me to an example where it is practical to apply both of these patterns and have them coexist together? If not, is it a bad practice?

Please do not direct me to a site giving me the dictionary definition of these patterns, I am well aware of each one, and there every day use, but have not ran into a situation where I have needed both. Thanks ahead of time.


Solution

  • Well, if you have one class that already uses a Factory Method and you'd like to implement that method with another predefined Abstract Factory, you can create an Adapter between the two:

    public class FactoryAdapter : ClassUsingFactoryMethod
    {
        private readonly IFactory factory;
    
        public FactoryAdapter(IFactory factory)
        {
            this.factory = factory;
        }
    
        protected override Foo CreateFoo()
        {
            return this.factory.Create();
        }
    }