空对象模式

 

 

 1 <?php
 2 
 3 abstract class Person
 4 {
 5     protected $_name;
 6 
 7     abstract public function getName();
 8 }
 9 
10 class RealPerson extends Person
11 {
12     function __construct($name)
13     {
14         $this->_name = $name;
15     }
16 
17     public function getName()
18     {
19         echo "我的名字是:{$this->_name}";
20     }
21 }
22 
23 class NullPerson extends Person
24 {
25     public function getName()
26     {
27         echo "<br/>我不是人类哦";
28     }
29 }
30 
31 
32 
33 
34 class Factory
35 {
36     private $_names = ['A', 'B', 'C'];
37 
38     public function produce($personName)
39     {
40         if (array_search($personName, $this->_names) !== false) {
41             return new RealPerson($personName);
42         }
43 
44         return new NullPerson();
45     }
46 }
47 
48 
49 
50 $f = new Factory();
51 $p1 = $f->produce('A');
52 $p1->getName();
53 
54 $p2 = $f->produce('G');
55 $p2->getName();
View Code

 

posted @ 2017-01-07 10:57  _logan  阅读(98)  评论(0编辑  收藏  举报