} else { throw new IllegalArgumentException("Unknown image type."); } } } PHP class Factory { public static function build($type) { $class = "Format" . $type; if (!class_exists($class)) { throw new Exception("Missing format class."); } return new $class; } } interface FormatInterface {} class FormatString implements FormatInterface {} class FormatNumber implements FormatInterface {} try { $string = Factory::build("String"); } catch (Exception $e) { echo $e->getMessage(); } try { $number = Factory::build("Number"); } catch (Exception $e) { echo $e->getMessage(); } Limitations There are three limitations associated with the use of the factory method. The first relates to refactoring existing code; the other two relate to extending a class. The first limitation is that refactoring an existing class to use factories breaks existing clients. For example, if class Complex were a standard class, it might have numerous clients with code like:Complex c = new Complex(-1, 0); Once we realize that two different factories are needed, we change the class (to the code shown earlier). But since the constructor is now private, the existing client code no longer compiles. The second limitation is that, since the pattern relies on using a private constructor, the class cannot be extended. Any subclass must invoke the inherited constructor, but this cannot be done if that constructor is private. The third limitation is that, if the class were to be extended (e.g., by making the constructor protected—this is risky but feasible), the subclass must provide its own re-implementation of all factory methods with exactly the same signatures. For example, if class StrangeComplex extends Complex, then unless StrangeComplex provides its own version of all factory methods, the call StrangeComplex.FromPolar(1, Math.Pi); will yield an instance of Complex (the superclass) rather than the expected instance of the subclass. The reflection features of some languages can avoid this issue. All three problems could be alleviated by altering the underlying programming language to make factories first-class class members (see also Virtual class). Notes References Object-oriented programming Articles with example C Sharp code Articles with example Java code Articles with example PHP code zh:工厂方法#工厂