PHP设计模式小结
PHP设计模式是面向对象编程的一种重要组成部分,它通过复用、扩展和抽象已有的代码解决常见的编程问题,提高了代码的可维护性、可读性和可重用性。本文将逐一介绍常见的PHP设计模式,并针对每一种设计模式进行示例说明,以便读者更好地理解。
工厂模式
工厂模式是一种用于创建对象的设计模式。它通过将对象的创建逻辑封装在一个工厂类中,使得对于外部调用者来说,只需要调用工厂类的方法,无需关心对象创建的具体过程。
示例一:创建不同类型的Logger对象
// Logger interface
interface Logger {
public function log($message);
}
// FileLogger class
class FileLogger implements Logger {
public function log($message) {
echo 'Log message to file: ' . $message . "\n";
}
}
// DbLogger class
class DbLogger implements Logger {
public function log($message) {
echo 'Log message to database: ' . $message . "\n";
}
}
// LoggerFactory class
class LoggerFactory {
public static function getLogger($type) {
if ($type == 'file') {
return new FileLogger();
} else if ($type == 'db') {
return new DbLogger();
} else {
throw new Exception('Invalid logger type');
}
}
}
// Usage
$logger1 = LoggerFactory::getLogger('file');
$logger1->log('Hello');
$logger2 = LoggerFactory::getLogger('db');
$logger2->log('World');
示例二:创建不同类型的Pizza对象
// Pizza abstract class
abstract class Pizza {
public abstract function prepare();
public abstract function bake();
public abstract function cut();
public abstract function box();
}
// CheesePizza class
class CheesePizza extends Pizza {
public function prepare() {
echo 'Preparing Cheese Pizza...' . "\n";
}
public function bake() {
echo 'Baking Cheese Pizza...' . "\n";
}
public function cut() {
echo 'Cutting Cheese Pizza...' . "\n";
}
public function box() {
echo 'Boxing Cheese Pizza...' . "\n";
}
}
// ClamPizza class
class ClamPizza extends Pizza {
public function prepare() {
echo 'Preparing Clam Pizza...' . "\n";
}
public function bake() {
echo 'Baking Clam Pizza...' . "\n";
}
public function cut() {
echo 'Cutting Clam Pizza...' . "\n";
}
public function box() {
echo 'Boxing Clam Pizza...' . "\n";
}
}
// PizzaFactory class
class PizzaFactory {
public static function createPizza($type) {
if ($type == 'cheese') {
return new CheesePizza();
} else if ($type == 'clam') {
return new ClamPizza();
} else {
throw new Exception('Invalid pizza type');
}
}
}
// Usage
$pizza1 = PizzaFactory::createPizza('cheese');
$pizza1->prepare();
$pizza1->bake();
$pizza1->cut();
$pizza1->box();
$pizza2 = PizzaFactory::createPizza('clam');
$pizza2->prepare();
$pizza2->bake();
$pizza2->cut();
$pizza2->box();
单例模式
单例模式是一种保证系统中只有一个实例对象的设计模式。它通过将构造函数私有化,并提供一个静态方法来获取实例对象,保证全局范围内只有一个实例对象存在。
示例:创建唯一的配置对象
// Config class
class Config {
private static $instance = null;
private $config = [];
private function __construct() {
$this->config = [
'db_host' => 'localhost',
'db_port' => '3306',
'db_user' => 'root',
'db_pass' => '123456',
'db_name' => 'mydb',
];
}
public static function getInstance() {
if (self::$instance == null) {
self::$instance = new Config();
}
return self::$instance;
}
public function get($key) {
return isset($this->config[$key]) ? $this->config[$key] : null;
}
}
// Usage
$config1 = Config::getInstance();
echo $config1->get('db_host') . "\n";
$config2 = Config::getInstance();
echo $config2->get('db_port') . "\n";
观察者模式
观察者模式是一种实现对象间“一对多”依赖关系的设计模式。它通过定义主题和观察者两个接口,使得主题在发生状态改变时通知所有注册的观察者对象,从而实现对象间的动态交互。
示例:实现股票行情更新的观察者模式
// Subject interface
interface Subject {
public function registerObserver($observer);
public function removeObserver($observer);
public function notifyObservers($data);
}
// Observer interface
interface Observer {
public function update($data);
}
// StockMarket class
class StockMarket implements Subject {
private $observers = [];
public function registerObserver($observer) {
$this->observers[] = $observer;
}
public function removeObserver($observer) {
$key = array_search($observer, $this->observers);
if ($key !== false) {
unset($this->observers[$key]);
}
}
public function notifyObservers($data) {
foreach ($this->observers as $observer) {
$observer->update($data);
}
}
public function updateStockPrice($symbol, $price) {
$data = [
'symbol' => $symbol,
'price' => $price
];
$this->notifyObservers($data);
}
}
// StockMonitor class
class StockMonitor implements Observer {
private $name = '';
public function __construct($name) {
$this->name = $name;
}
public function update($data) {
echo $this->name . ': Stock price update - Symbol: ' . $data['symbol'] . ', Price: ' . $data['price'] . "\n";
}
}
// Usage
$market = new StockMarket();
$google = new StockMonitor('Google');
$apple = new StockMonitor('Apple');
$market->registerObserver($google);
$market->registerObserver($apple);
$market->updateStockPrice('GOOG', 1342.48);
$market->updateStockPrice('AAPL', 309.63);
$market->removeObserver($google);
$market->updateStockPrice('AAPL', 311.34);
迭代器模式
迭代器模式是一种访问集合对象元素的设计模式。它通过定义迭代器接口和集合接口,将集合对象的内部结构和外部访问分离,从而实现对集合对象的遍历访问。
示例:实现数组访问的迭代器模式
// Iterator interface
interface Iterator {
public function hasNext();
public function next();
}
// Collection interface
interface Collection {
public function add($item);
public function remove($item);
public function getIterator();
}
// ArrayIterator class
class ArrayIterator implements Iterator {
private $arr = [];
private $index = 0;
public function __construct($arr) {
$this->arr = $arr;
}
public function hasNext() {
return $this->index < count($this->arr);
}
public function next() {
return $this->arr[$this->index++];
}
}
// ArrayCollection class
class ArrayCollection implements Collection {
private $items = [];
public function add($item) {
$this->items[] = $item;
}
public function remove($item) {
$key = array_search($item, $this->items);
if ($key !== false) {
unset($this->items[$key]);
}
}
public function getIterator() {
return new ArrayIterator($this->items);
}
}
// Usage
$collection = new ArrayCollection();
$collection->add(1);
$collection->add(2);
$collection->add(3);
$iterator = $collection->getIterator();
while ($iterator->hasNext()) {
echo $iterator->next() . "\n";
}
策略模式
策略模式是一种将算法封装起来,使得它们可以相互替换而不影响客户端的设计模式。它通过定义策略接口和策略实现类,以及上下文类来组合策略和客户端使用策略的能力。
示例:实现不同加密方式的策略模式
// EncryptionStrategy interface
interface EncryptionStrategy {
public function encrypt($text);
}
// SimpleEncryption class
class SimpleEncryption implements EncryptionStrategy {
public function encrypt($text) {
return strrev($text);
}
}
// SHA256Encryption class
class SHA256Encryption implements EncryptionStrategy {
public function encrypt($text) {
return hash('sha256', $text);
}
}
// EncryptionContext class
class EncryptionContext {
private $strategy = null;
public function __construct(EncryptionStrategy $strategy) {
$this->strategy = $strategy;
}
public function setStrategy(EncryptionStrategy $strategy) {
$this->strategy = $strategy;
}
public function encrypt($text) {
return $this->strategy->encrypt($text);
}
}
// Usage
$context1 = new EncryptionContext(new SimpleEncryption());
echo $context1->encrypt('hello') . "\n";
$context2 = new EncryptionContext(new SHA256Encryption());
echo $context2->encrypt('world') . "\n";
以上就是本文对于常见的PHP设计模式的详细介绍和示例解析。其它常见的设计模式如模板方法、装饰器、代理等也可参考相关文献学习。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:php设计模式小结 - Python技术站