designModeDemo/demo/Creational/FactoryMethod/Run.php

44 lines
1.4 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace demo\Creational\FactoryMethod;
class Run extends \bin\Design
{
/**
* 对比简单工厂模式的优点是,您可以将其子类用不同的方法来创建一个对象。
* 举一个简单的例子,这个抽象类可能只是一个接口。
* 这种模式是「真正」的设计模式, 因为他实现了 S.O.L.I.D 原则中「D」的 「依赖倒置」。
* 这意味着工厂方法模式取决于抽象类,而不是具体的类。 这是与简单工厂模式和静态工厂模式相比的优势。
*
* @inheritDoc
*/
public function setDesignName() : string
{
return '工厂方法模式Factory Method';
}
/**
* @inheritDoc
*/
public function setDesignRefUrl() : string
{
return 'https://learnku.com/docs/php-design-patterns/2018/FactoryMethod/1489';
}
/**
* @inheritDoc
*/
public function main()
{
(new StdoutLogger)->log('测试日志打印');
$loggerFactory = new StdoutLoggerFactory();
$logger = $loggerFactory->createLogger();
// 判断类型是否一样
dump(StdoutLogger::class instanceof $logger);
$loggerFactory = new FileLoggerFactory(sys_get_temp_dir());
$logger = $loggerFactory->createLogger();
dump(FileLogger::class instanceof $logger);
}
}