PHP代码:
<?php
abstract class AbstractCustomer{
protected $name;
public abstract function isNil();
public abstract function getName();
}
class RealCustomer extends AbstractCustomer {
public function __construct($name)
{
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function isNil() {
return false;
}
}
class NullCustomer extends AbstractCustomer {
public function getName() {
return "Not Available in Customer Database";
}
public function isNil() {
return true;
}
}
class CustomerFactory {
#PHP中final不能修饰变量,但可以是类和方法
public static $names = ["Rob", "Joe", "Julie"];
public static function getCustomer($name){
//foreach更方便,如果说有点学习点地方就是静态变量必须用静态方法调用,self::$value
for ($i = 0; $i < count(self::$names); $i++) {
if (self::$names[$i] == $name){
return new RealCustomer($name);
}
}
return new NullCustomer();
}
}
class NullPatternDemo {
public static function main() {
$customer1 = CustomerFactory::getCustomer("Rob");
$customer2 = CustomerFactory::getCustomer("Bob");
$customer3 = CustomerFactory::getCustomer("Julie");
$customer4 = CustomerFactory::getCustomer("Laura");
echo "Customers".PHP_EOL;
echo $customer1->getName().PHP_EOL;
echo $customer2->getName().PHP_EOL;
echo $customer3->getName().PHP_EOL;
echo $customer4->getName().PHP_EOL;
}
}
NullPatternDemo::main();
/* * 执行程序,输出结果:
localhost:bin fangliang$ php /Users/fangliang/Downloads/test.php
Customers Rob
Not Available in Customer Database
Julie
Not Available in Customer Database
* * */
1846

被折叠的 条评论
为什么被折叠?



