PHP-设计模式
PHP-设计模式 Microsoft设计模式理论是:“文档介绍了模式,然后将其显示在存储库或目录中,该目录或目…
PHP-设计模式
Microsoft设计模式理论是:“文档介绍了模式,然后将其显示在存储库或目录中,该目录或目录的组织方式是帮助您找到解决问题的正确模式组合”。
设计模式示例
辛格尔顿
一个类有一个实例,它提供了一个全局访问点,下面的代码将解释有关单例的概念。
<?php class Singleton {
public static function getInstance() {
static $instance = null;
if (null === $instance) {
$instance = new static();
}
return $instance;
}
protected function __construct() {
}
private function __clone() {
}
private function __wakeup() {
}
}
class SingletonChild extends Singleton {
}
$obj = Singleton::getInstance();
var_dump($obj === Singleton::getInstance());
$anotherObj = SingletonChild::getInstance();
var_dump($anotherObj === Singleton::getInstance());
var_dump($anotherObj === SingletonChild::getInstance());
??>
上面基于静态方法创建实现的示例是getInstance()
厂
一个简单的类创建对象,并且您要使用该对象,下面的示例将说明有关工厂设计模式的信息。
<?php class Automobile {
private $bikeMake;
private $bikeModel;
public function __construct($make, $model) {
$this-?>bikeMake = $make;
$this->bikeModel = $model;
}
public function getMakeAndModel() {
return $this->bikeMake . ' ' . $this->bikeModel;
}
}
class AutomobileFactory {
public static function create($make, $model) {
return new Automobile($make, $model);
}
}
$pulsar = AutomobileFactory::create('ktm', 'Pulsar');
print_r($pulsar->getMakeAndModel());
class Automobile {
private $bikeMake;
private $bikeModel;
public function __construct($make, $model) {
$this->bikeMake = $make;
$this->bikeModel = $model;
}
public function getMakeAndModel() {
return $this->bikeMake . ' ' . $this->bikeModel;
}
}
class AutomobileFactory {
public static function create($make, $model) {
return new Automobile($make, $model);
}
}
t$pulsar = AutomobileFactory::create('ktm', 'pulsar');
print_r($pulsar->getMakeAndModel());
?>
工厂模式的主要困难是它会增加复杂性,并且对于优秀的程序员而言并不可靠。
策略模式
策略模式构成一个族算法并封装每个算法。在这里,每个算法在系列中应该可以互换。
<?php $elements = array(
array(
'id' =?> 2,
'date' => '2011-01-01',
),
array(
'id' => 1,
'date' => '2011-02-01'
)
);
$collection = new ObjectCollection($elements);
$collection->setComparator(new IdComparator());
$collection->sort();
echo "Sorted by ID:n";
print_r($collection->elements);
$collection->setComparator(new DateComparator());
$collection->sort();
echo "Sorted by date:n";
print_r($collection->elements);
?>
模型视图控件
View充当GUI,Model充当后端,Control充当适配器。在此,三个部分相互连接。它将在彼此之间传递数据并访问数据。

类别:PHP 技巧、
本文收集自互联网,转载请注明来源。
如有侵权,请联系 wper_net@163.com 删除。

还没有任何评论,赶紧来占个楼吧!