Search code examples
design-patternsfactory-pattern

factory pattern - avoid type specific condition


Please help me how can I skip these conditions?

I am using factory pattern.

pizza = pizzaFctory.create ('xxx'); # e.g. these types are a,b,c,d

now I call a function

pizza->verifySomething ('yyy');

Here is my question: the argument 'foo' is different for different types (a,b,c,d). e.g. if argument to create() is 'a' then argument to verifySomething 'fooa'. Similarly, if argument to create() is 'b' then argument to verifySomething 'foob'.

I understand that I can put one condition and verify it.

  if (pizza->isTypeA)
  {
    pizza->verifySomething ('fooa');
  }

I want to avoid this if condition. Please tell me some ways to achieve it.


Solution

  • public abstract Pizza
    {
        public abstract bool VerifySomething( object obj );
    }
    
    public class APizza : Pizza
    {
        public bool VerifySomething( object obj )
        {
            FooA foo = (FooA)obj;
            ...
        }
    }
    
    public class BPizza : Pizza
    {
        public bool VerifySomething( object obj )
        {
            FooB foo = (FooB)obj;
            ...
        }
    }
    

    If all of the types of pizza can't have a VerifySomething method they you may be violating the Liskov Substitution Principle (LSP). There may be a better way to separate your classes that will make this more obvious.