首页 > 其他 > 详细

设计模式 工厂模式

时间:2020-05-26 22:52:31      阅读:51      评论:0      收藏:0      [点我收藏+]

转自:https://github.com/domnikl/DesignPatternsPHP

 1 interface Logger
 2 {
 3     public function log(string $message);
 4 }
 5 
 6 class FileLogger implements Logger
 7 {
 8     private string $filePath;
 9 
10     public function __construct(string $filePath)
11     {
12         $this->filePath = $filePath;
13     }
14 
15     public function log(string $message)
16     {
17         file_put_contents($this->filePath, $message . PHP_EOL, FILE_APPEND);
18     }
19 }
20 
21 class StdoutLogger implements Logger
22 {
23     public function log(string $message)
24     {
25         echo $message;
26     }
27 }
 1 class FileLoggerFactory implements LoggerFactory
 2 {
 3     private string $filePath;
 4 
 5     public function __construct(string $filePath)
 6     {
 7         $this->filePath = $filePath;
 8     }
 9 
10     public function createLogger(): Logger
11     {
12         return new FileLogger($this->filePath);
13     }
14 }
15 
16 interface LoggerFactory
17 {
18     public function createLogger(): Logger;
19 }
20 
21 class StdoutLoggerFactory implements LoggerFactory
22 {
23     public function createLogger(): Logger
24     {
25         return new StdoutLogger();
26     }
27 }
 1 class FactoryMethodTest extends TestCase
 2 {
 3     public function testCanCreateStdoutLogging()
 4     {
 5         $loggerFactory = new StdoutLoggerFactory();
 6         $logger = $loggerFactory->createLogger();
 7 
 8         $this->assertInstanceOf(StdoutLogger::class, $logger);
 9     }
10 
11     public function testCanCreateFileLogging()
12     {
13         $loggerFactory = new FileLoggerFactory(sys_get_temp_dir());
14         $logger = $loggerFactory->createLogger();
15 
16         $this->assertInstanceOf(FileLogger::class, $logger);
17     }
18 }

 

设计模式 工厂模式

原文:https://www.cnblogs.com/ts65214/p/12968463.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!