设计模式 工厂模式

转自: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 }

 

posted @ 2020-05-26 20:24  是的哟  阅读(135)  评论(0)    收藏  举报