常用的四种设计模式 PHP代码
// 工厂模式 interface Iuser { public function getUserName(); } class UserFactory { static public function load($className) { return new strtolower($className); } static public function create($className) { return new strtolower($className); } } class User implements Iuser { public function getUserName() { return 'jack'; } } UserFactory::create('User')->getUserName(); // 单例模式 class Singleton { static public function getInstance() { static $obj = null; if($obj == null) { return new Singleton(); } return $obj; } public function getUserName() { return 'jack'; } } Singleton::getInstance()->getUserName(); // 观察者模式 interface Observe { public function getUserName(); } class User { private $servs = []; public function register($obj) { array_push($servs, $obj); return $this; } public function triggle() { if($this->servs) { foreach($this->servs as $key => $value) { $value->getUserName(); } } } } Class MyUser extends User implements Observ { public function getUserName() { return 'jack'; } } (new User())->register(new MyUser)->triggle();
// 策略模式 interface Human { function speak(); } class Chinese implements Human { public function speak() { echo '中国人说中文'; } } class American implements Human { public function speak() { echo '美国人说英文'; } }