Magento 2对非注射剂使用工厂类。
例如产品类别:ProductFactory
例如客户类别:CustomerFactory
我不明白这里的工厂模式是什么?
因为对于与1个工厂类关联的每个类。我在想它有些重复。
为什么我们不应该创建抽象工厂CustomerFactory,ProductFactory等等?
并且例如:
我们可以通过AbstractFactory进行类型检查,而不是ProductFactory在ProductRepository类的构造函数。
因此我们可以避免ProductRepository和之间的紧密耦合ProductFactory
抽象工厂类:
namespace Magento\Framework\ObjectManager\Code\Generator;
/**
 * Abstract Factory class 
 */
abstract class AbstractFactory 
{
    /**
     * Object Manager instance
     *
     * @var \Magento\Framework\ObjectManagerInterface
     */
    protected $_objectManager = null;
    /**
     * Instance name to create
     *
     * @var string
     */
    protected $_instanceName = null;
    /**
     * Create class instance with specified parameters
     *
     * @param array $data
     * @return \Magento\Catalog\Model\Product
     */
    public function create(array $data = array())
    {
        return $this->_objectManager->create($this->_instanceName, $data);
    }
}
抽象工厂实现:
namespace Magento\Catalog\Model;
use Magento\Framework\ObjectManager\Code\Generator\AbstractFactory;
/**
 * Factory class for @see \Magento\Catalog\Model\Product
 */
class ProductFactory extends AbstractFactory
{
    public function __construct(\Magento\Framework\ObjectManagerInterface $objectManager, $instanceName = '\\Magento\\Catalog\\Model\\Product')
    {
        $this->_objectManager = $objectManager;
        $this->_instanceName = $instanceName;
    }
}
对象管理器和工厂之间是什么关系?
链接对象太多了:
例如
ProductRepository(在这里我们可以称其为客户端)requireProduct对象。为此,它取决于特定的
ProductFactory对象。ProductFactory对象取决于ObjectManager对象。ObjectManager对象取决于Factory对象(此处为Developer Object)。
当然,他们使用接口进行松耦合。仍然令人困惑。
您是否可以利用Magento 2工厂模式深入了解其优势,以及它与Magento 1有何不同?