码迷,mamicode.com
首页 > Web开发 > 详细

PHP设计模式

时间:2016-05-13 17:11:37      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

1.单例模式

 1 <?php
 2 class Mysql{
 3     private static $instance = null;
 4     private $conn;
 5     //构造方法,设置为private,不允许通过new获得对象
 6     private function __construct(){
 7         $conn = mysql_connect("localhost", "root", "");
 8     }
 9     public static function getInstance(){
10         if(!self::$instance instanceof self){
11             self::$instance = new self;
12         }
13         return self::$instance;
14     }
15     //阻止用户复制对象实例
16     private function __clone(){}
17 }
18 $db = Mysql::getInstance();
19 ?>

2.工厂模式

 1 <?php
 2 //定义个抽象类,让子类去继承实现它
 3 abstract class Operation{
 4     abstract public function getValue($num1, $num2);//子类必须实现此方法
 5 }
 6 
 7 //加法类
 8 class OperationAdd extends Operation{
 9     public function getValue($num1, $num2){
10         return $num1+$num2;
11     }
12 }
13 //减法类
14 class OperationSub extends Operation{
15     public function getValue($num1, $num2){
16         return $num1-$num2;
17     }
18 }
19 //乘法类
20 class OperationMul extends Operation{
21     public function getValue($num1, $num2){
22         return $num1*$num2;
23     }
24 }
25 //除法类
26 class OperationDiv extends Operation{
27     public function getValue($num1, $num2){
28         try{
29             if($num2 == 0){
30                 throw new Exception("除数不能为0");
31             }else{
32                 return $num1/$num2;
33             }
34         }catch(Exception $e){
35             echo "错误信息:".$e->getMessage();
36         }
37     }
38 }
39 /**
40  *  工厂类,主要用来创建对象
41  *  功能:根据输入的运算符号,工厂就能实例出合适的对象
42  */
43 class Factory{
44     public static function createObj($operate){
45         switch($operate){
46             case ‘+‘:
47                 return new OperationAdd();
48                 break;
49             case ‘-‘:
50                 return new OperationSub();
51                 break;
52             case ‘*‘:
53                 return new OperationMul();
54                 break;
55             case ‘/‘:
56                 return new OperationDiv();
57                 break;
58         }
59     }
60 }
61 $test=Factory::createObj(‘/‘);
62 $result=$test->getValue(23,0);
63 echo $result;
64 ?>

 

PHP设计模式

标签:

原文地址:http://www.cnblogs.com/starryyy/p/5489942.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!