[php]php设计模式 Factory(工厂模式)

1 <?php
2 /**
3 * 工厂方法模式
4 *
5 * 定义一个用于创建对象的接口,让子类决定将哪一个类实例化,使用一个类的实例化延迟到其子类
6 */
7
8 /*
9 class DBFactory
10 {
11 public static function create($type)
12 {
13 swtich($type)
14 {
15 case "Mysql":
16 return new MysqlDB(); break;
17 case "Postgre":
18 return new PostgreDB(); break;
19 case "Mssql":
20 return new MssqlDB(); break;
21 }
22 }
23 }
24 */
25 class DBFactory
26 {
27 publicstaticfunction create($type)
28 {
29 $class=$type."DB";
30 returnnew$class;
31 }
32 }
33
34 interface DB
35 {
36 publicfunction connect();
37 publicfunctionexec();
38 }
39
40 class MysqlDB implements DB
41 {
42 publicfunction __construct() {
43 echo"mysql db<br/>";
44 }
45
46 publicfunction connect() {
47 }
48
49 publicfunctionexec() {
50 }
51 }
52
53 class PostgreDB implements DB
54 {
55 publicfunction __construct() {
56 echo"Postgre db<br/>";
57 }
58
59 publicfunction connect() {
60 }
61
62 publicfunctionexec() {
63 }
64 }
65
66 class MssqlDB implements DB
67 {
68 publicfunction __construct() {
69 echo"mssql db<br/>";
70 }
71
72 publicfunction connect() {
73 }
74 publicfunctionexec() {
75 }
76 }
77
78
79 $oMysql= DBFactory::create("Mysql");
80 $oPostgre= DBFactory::create("Postgre");
81 $oMssql= DBFactory::create("Mssql");

posted on 2011-01-04 23:22  bluefrog  阅读(3477)  评论(0编辑  收藏  举报