工厂方法中 switch 语句的 default case 应该包含什么?

What should go into default case of a switch statement inside a Factory Method?

当我所有的对象创建参数都定义明确时,工厂方法工作得很好。但是,使用遗留代码时,默认设置似乎是 'fail silently' 或编写防止无效数据到达工厂方法的代码结构。

工厂方法中 switch 语句的 default: 情况通常包含什么?

下面的例子...

class Factory
{

    function getObject($param)
    {
        switch ($param)
        {
            case 'a':
                return new A();
            case 'b':
                return new B();
            default:

                //OPTION 1
                //break code execution?  Sometimes it's not desirable
                //especially in production code as introducing an
                //Exception breaks previous legacy code behavior
                throw new \RuntimeException($message, $code, $previous);

                //OPTION 2
                //fail silently? - sometimes that's the desired behavior
                //dummy object is created does nothing, and is then 
                //discarded and code execution goes on, but creating 
                //a dummy object does not seems like the right way to address the issue
                return new fakeDummyObject(); 

                //OPTION 3
                //3rd way is to construct code that never reaches 
                //default:; switch statement.  This requires
                //more work on the legacy code side
        }
    }
}

抛出一个InvalidArgumentException。有人试图实例化一种您的工厂不知道的对象。

如果我正确理解

class Factory
{

    private $_classes = array();

    function getObject($param,$constParam = null)
    {
        //check exist object exist
        if(isset($this->_classes[$param])) {
            return $this->_classes[$param];
        } 

        $className =  strtoupper($param);
        //check class exist
        if(!class_exists($className)) {
            return new fakeClass(); //or exception
        }

        // if don't passed params to construct
        if(is_null($constParam)) {
           $this->_classes[$param] = new $className();
           return $this->_classes[$param];
        }

        // else params passed to construct
        $this->_classes[$param] = new $className($constParam);
        return $this->_classes[$param];
    }
}

它是对象的原始实现函数getter...如果我没看错你就明白了