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