php 示例

最后更新于:2022-04-02 04:18:54

[TOC] ## 示例 ### 概念示例
index.php ``` factoryProduct(); return $product->operation(); } } class CreatorProduct1 extends Creator{ public function factoryProduct():Product{ return new Product1(); } } class CreatorProduct2 extends Creator{ public function factoryProduct():Product{ return new Product2(); } } function clientCode(Creator $create){ $product = $create->factoryProduct(); echo $product->operation(); } clientCode(new CreatorProduct1()); //Product1 clientCode(new CreatorProduct2()); // Product2 ```

### 社交网络连接器
index.php ``` getSocialNetwork(); // ...then use it as you will. $network->logIn(); $network->createPost($content); $network->logout(); } } class FacebookPoster extends SocialNetworkPoster { private $login, $password; public function __construct(string $login, string $password) { $this->login = $login; $this->password = $password; } public function getSocialNetwork(): SocialNetworkConnector { return new FacebookConnector($this->login, $this->password); } } // LinkedIn class LinkedInPoster extends SocialNetworkPoster { private $email, $password; public function __construct(string $email, string $password) { $this->email = $email; $this->password = $password; } public function getSocialNetwork(): SocialNetworkConnector { return new LinkedInConnector($this->email, $this->password); } } interface SocialNetworkConnector { public function logIn(): void; public function logOut(): void; public function createPost($content): void; } class FacebookConnector implements SocialNetworkConnector { private $login, $password; public function __construct(string $login, string $password) { $this->login = $login; $this->password = $password; } public function logIn(): void { echo "logIn:$this->login with password $this->password \n"; } public function logOut(): void { echo "logOut:$this->login\n\n"; } public function createPost($content): void { echo "createPost:{$content}\n"; } } class LinkedInConnector implements SocialNetworkConnector { private $email, $password; public function __construct(string $email, string $password) { $this->email = $email; $this->password = $password; } public function logIn(): void { echo "logIn: $this->email $this->password\n"; } public function logOut(): void { echo "logOut: $this->email\n\n"; } public function createPost($content): void { echo "createPost: $content\n"; } } function clientCode(SocialNetworkPoster $creator) { // ... $creator->post("Hello world!"); $creator->post("I had a large hamburger this morning!"); // ... } clientCode(new FacebookPoster("john_smith", "******")); echo "\n\n"; clientCode(new LinkedInPoster("john_smith@example.com", "******")); ```

';