作为一门广泛应用的编程语言,php 可以轻松的用于实现面向对象编程(object-oriented programming, oop)。 而在使用 oop 进行开发时,一个程序员需要深入理解设计模式这一概念。 设计模式是指在特定情况下,通用的解决某类问题的方案。那么本文将介绍使用 php 实现的几种常用设计模式。
单例模式(singleton pattern)在单例模式中,一个类仅有一个实例。当一些情况下实例的重复创建会带来程序性能上的消耗,而且每个实例都能在并发情况下应用不同的状态,这时候就需要用到单例模式。
以下是单例模式的示例代码:
class singleton { private static $instance; private function __construct() {} public static function getinstance() { if (!isset(self::$instance)) { self::$instance = new singleton(); } return self::$instance; }}
在上述代码中,getinstance 函数将创建一个单例,并确保在应用程序中只能有一个类实例。
工厂模式(factory pattern)工厂模式是将对象的创建过程封装在一个工厂类中,使得工厂类和具体类分离,减少耦合度。在工厂模式中,一个工厂类可以创建多个类别的实例。
下面是工厂模式的示例代码:
interface shape { public function draw();}class circle implements shape { public function draw() { echo "circle"; }}class rectangle implements shape { public function draw() { echo "rectangle"; }}class shapefactory { public function createshape($type) { if ($type == 'circle') { return new circle(); } else if ($type == 'rectangle') { return new rectangle(); } }}$shapefactory = new shapefactory();$circle = $shapefactory->createshape('circle');$rectangle = $shapefactory->createshape('rectangle');$circle->draw(); //output: circle$rectangle->draw(); //output: rectangle
观察者模式(observer pattern)观察者模式是在一个对象被修改时自动通知其他对象的一种模式。在观察者模式中,一个被观察的对象可以有多个观察者,当状态改变时,这些观察者会收到通知并自动更新。
以下是观察者模式的示例代码:
interface subject { public function attach(observer $observer); public function detach(observer $observer); public function notify();}class concretesubject implements subject { private $observers = []; public function attach(observer $observer) { $this->observers[] = $observer; } public function detach(observer $observer) { $key = array_search($observer, $this->observers); if ($key !== false) { unset($this->observers[$key]); } } public function notify() { foreach ($this->observers as $observer) { $observer->update(); } }}interface observer { public function update();}class concreteobserver implements observer { public function update() { echo "updated!"; }}$subject = new concretesubject();$observer1 = new concreteobserver();$observer2 = new concreteobserver();$subject->attach($observer1);$subject->attach($observer2);$subject->notify(); //output: updated! updated!$subject->detach($observer2);$subject->notify(); //output: updated!
在上述代码中, subject 和 observer 都是接口,主要用于固定观察者模式的结构, concretesubject 是一个具体类,用于被观察, concreteobserver 是一个具体观察者类。
在 php 中,设计模式可以用得十分灵活。以上三种设计模式只是使用 php 实现的一小部分常见设计模式的示例,程序员们在实际开发中需要深入理解设计模式的概念,从而选择恰当的模式并应用到程序中以解决实际问题。
以上就是用php实现面向对象编程的常用设计模式的详细内容。