protected function createFactory()
    {
        if (!class_exists($this->factoryClass)) {
            throw new RuntimeException(sprintf(
                'Failed to create an instance of non-existing factory class "%s".',
                $this->factoryClass
            ));
        }

        $class = $this->factoryClass;

        switch (count($this->args)) {
            case 0:
                $factory = new $class();
                break;

            case 1:
                $factory = new $class($this->args[0]);
                break;

            case 2:
                $factory = new $class($this->args[0], $this->args[1]);
                break;

            case 3:
                $factory = new $class($this->args[0], $this->args[1], $this->args[2]);
                break;

            case 4:
                $factory = new $class($this->args[0], $this->args[1], $this->args[2], $this->args[3]);
                break;

            default:
                $reflection = new ClassReflection($class);
                $factory = $reflection->newInstanceArgs($this->args);
                break;
        }

        if (!$factory instanceof FactoryInterface) {
            throw new LogicException(sprintf(
                'Invalid service factory. Factory is expected to be an instance of %s, %s given.',
                'Zend\ServiceManager\FactoryInterface',
                get_class($factory)
            ));
        }

        return $factory;
    }