final class StaticFactory\n{\n public static function factory(string $type): Formatter\n {\n if ($type == \'number\') {\n return new FormatNumber();\n } elseif ($type == \'string\') {\n return new FormatString();\n }\n\n throw new InvalidArgumentException(\'Unknown format given\');\n }\n}
interface Book\n{\n public function turnPage();\n}\ninterface EBook\n{\n public function pressNext();\n}
Kindle类实现了EBook
class Kindle implements EBook\n{\n public function pressNext(){\n }\n}\nclass EBookAdapter implements Book\n{\n protected EBook $eBook;\n\n public function __construct(EBook $eBook)\n {\n $this->eBook = $eBook;\n }\n\n public function turnPage()\n {\n $this->eBook->pressNext();\n }\n}
转换并使用
$kindle = new Kindle();\n$book = new EBookAdapter($kindle);\n$book->turnPage();
class User{\n private string $username;\n private string $email;\n //将数组转成对象\n public static function fromState(array $state): User\n {\n return new self(\n $state[\'username\'],\n $state[\'email\']\n );\n }\n //通过构造函数获取对象\n public function __construct(string $username, string $email){\n $this->username = $username;\n $this->email = $email;\n }\n\n public function getUsername(): string{\n return $this->username;\n }\n\n public function getEmail(): string{\n return $this->email;\n }\n}
这个是数据的映射,将存储中的数据映射到对象的中间那层
class UserMapper{\n private StorageAdapter $adapter;\n public function __construct(StorageAdapter $storage){\n $this->adapter = $storage;\n }\n public function findById(int $id): User{\n $result = $this->adapter->find($id);\n return $this->mapRowToUser($result);\n }\n private function mapRowToUser(array $row): User{\n return User::fromState($row);\n }\n}
这个是数据的访问
class StorageAdapter\n{\n private array $data = [];\n\n public function __construct(array $data)\n {\n $this->data = $data;\n }\n public function find(int $id)\n {\n if (isset($this->data[$id])) {\n return $this->data[$id];\n }\n }\n}
使用的过程$user就是最终的对象
$storage = new StorageAdapter([1 => [\'username\' => \'陶士涵\', \'email\' => \'[email protected]\']]);\n$mapper = new UserMapper($storage);\n$user = $mapper->findById(1);