0

Like the BeanFactory in java:

In the much more common case where the BeanFactory itself directly creates the bean by calling its constructor (equivalent to Java code calling new), the class attribute specifies the class of the bean to be constructed. In the less common case where the BeanFactory calls a static, so-called factory method on a class to create the bean, the class attribute specifies the actual class containing the static factory method.

Note:it's not the factory method

$instance = new FactoryClass();

The $instance may be any class instance dynamically

4

2 回答 2

1

您可以将 __autoload 与静态方法结合使用。这被过度简化了。

我的对象.php:

<?php
class MyObject
{
    public static function Create()
    {
        return new MyObject();
    }

    public function hello()
    {
        print('hello!!!');
    }
}

索引.php

<?php
function __autoload($className)
{
    require_once($className . '.php');
}

$o = MyObject::Create();
$o->hello();
于 2010-03-21T06:20:02.150 回答
0

It's the worlds crappiest website, but this seems to contain what you want: http://www.devshed.com/c/a/PHP/Design-Patterns-in-PHP-Factory-Method-and-Abstract-Factory/

See the actual website for usage examples, but more or less similar to the java factory.


// define abstract 'ArrayFactory' class
abstract class ArrayFactory{
   abstract public function createArrayObj($type); 
}

// define concrete factory to create numerically-indexed array
objects
class NumericArrayFactory extends ArrayFactory{
   private $context='numeric';
   public function createArrayObj($type){
     $arrayObj=NULL;
     switch($type){
       case "uppercase";
         $arrayObj=new UppercasedNumericArrayObj();
         break;
       case "lowercase";
         $arrayObj=new LowercasedNumericArrayObj();
         break;
       default:
         $arrayObj=new LowercasedNumericArrayObj();
         break; 
     }
     return $arrayObj;
   }
}

// define concrete factory to create associative array objects
class AssociativeArrayFactory extends ArrayFactory{
   private $context='associative';
   public function createArrayObj($type){
     $arrayObj=NULL;
     switch($type){
       case "uppercase";
         $arrayObj=new UppercasedAssociativeArrayObj();
         break;
       case "lowercase";
         $arrayObj=new LowercasedAssociativeArrayObj();
         break;
       default:
         $arrayObj=new LowercasedAssociativeArrayObj();
         break; 
     }
     return $arrayObj;
   }
}
于 2010-03-21T05:36:27.793 回答