《Head First 设计模式》代码之PHP版(面向对象学习)第1/2页_php技巧

书中的例子都比较浅显易懂,不过由于是外国佬写的,所以例子的习惯不是很附合中国特色,可能偶尔看起来有些别扭,还有语言习惯也不是中国风。当然��看过这本书之后,你才能深刻理解设计模式到底能为你解决哪些问题,不能为你解决哪些问题(比如不能代替你的编码)。
  我将书中部分代码改成PHP,看下代码再配合概念应该是比较容易理解了。

策略模式

复制代码 代码如下:

<?php
/**
* 策略模式
* 定义了算法族,分别封装起来,让它们之间可以互相替换,
* 此模式让算法的变化独立于使用算法的客户。
*/
//飞行行为接口
interface FlyBehavior {
public function fly();
}
//呱呱叫行为接口
interface QuackBehavior {
public function quack();
}
//翅膀飞行
class FlyWithWings implements FlyBehavior {
public function fly() {
echo "I'm flying!!\n";
}
}
//不会飞
class FlyNoWay implements FlyBehavior {
public function fly() {
echo "I can't fly!\n";
}
}
class FlyRocketPowered implements FlyBehavior {
public function fly() {
echo "I'm flying with a rocket!\n";
}
}
class Qquack implements QuackBehavior {
public function quack() {
echo "Quack\n";
}
}
class Squeak implements QuackBehavior {
public function quack() {
echo "Squeak\n";
}
}
class MuteQuack implements QuackBehavior {
public function quack() {
echo "<< Silence >>\n";
}
}
abstract class Duck {
protected $quack_obj;
protected $fly_obj;
public abstract function display();

public function performQuack() {
$this->quack_obj->quack();
}
public function performFly() {
$this->fly_obj->fly();
}
public function swim() {
echo "All ducks float, even decoys!\n";
}
public function setFlyBehavior(FlyBehavior $fb) {
$this->fly_obj = $fb;
}
public function setQuackBehavior(QuackBehavior $qb) {
$this->quack_obj = $qb;
}
}

class ModelDuck extends Duck {
public function __construct() {
$this->fly_obj = new FlyNoWay();
$this->quack_obj = new MuteQuack();
}
public function display() {
echo "I'm a model duck!\n";
}
}

$model = new ModelDuck();
$model->performFly();
$model->performQuack();
//提供新的能力
$model->setFlyBehavior(new FlyRocketPowered());
$model->setQuackBehavior(new Squeak());
$model->performFly();
$model->performQuack();

?>

单件模式

复制代码 代码如下:

<?php
/**
* 单件模式
* 确保一个类只有一个实例,并提供一个全局访问点。
*/
class MyClass {
private static $uniqueInstance;
private function __construct() {

}
public static function getInstance() {
if (self::$uniqueInstance == null) {
self::$uniqueInstance = new MyClass();
}
return self::$uniqueInstance;
}
}
$myClass = MyClass::getInstance();
var_dump($myClass);
$myClass = MyClass::getInstance();
var_dump($myClass);
?>

工厂方法模式

复制代码 代码如下:

<?php
abstract class PizzaStore {
public function orderPizza($type) {
$pizza = $this->createPizza($type);

$pizza->prepare();
$pizza->bake();
$pizza->cut();
$pizza->box();
return $pizza;
}

public abstract function createPizza($type);
}
class NYPizzaStore extends PizzaStore {
public function createPizza($type) {
if ($type == "cheese") {
return new NYStyleCheesePizza();
} elseif ($type == "veggie") {
return new NYStyleVeggiePizza();
} elseif ($type == "clam") {
return new NYStyleClamPizza();
} elseif ($type == "papperoni") {
return new NYStylePapperoniPizza();
} else {
return null;

}
}
}
class ChicagoPizzaStore extends PizzaStore {
public function createPizza($type) {
if ($type == "cheese") {
return new ChicagoStyleCheesePizza();
} elseif ($type == "veggie") {
return new ChicagoStyleVeggiePizza();
} elseif ($type == "clam") {
return new ChicagoStyleClamPizza();
} elseif ($type == "papperoni") {
return new ChicagoStylePapperoniPizza();
} else {
return null;
}
}
}
abstract class Pizza {
public $name;
public $dough;
public $sauce;
public $toppings = array();

public function prepare() {
echo "Preparing " . $this->name . "\n";
echo "Yossing dough...\n";
echo "Adding sauce...\n";
echo "Adding toppings: \n";
for ($i = 0; $i < count($this->toppings); $i++) {
echo " " . $this->toppings[$i] . "\n";
}
}

public function bake() {
echo "Bake for 25 minutes at 350\n";
}

public function cut() {
echo "Cutting the pizza into diagonal slices\n";
}

public function box() {
echo "Place pizza in official PizzaStore box\n";
}

public function getName() {
return $this->name;
}
}

class NYStyleCheesePizza extends Pizza {
public function __construct() {
$this->name = "NY Style Sauce and cheese Pizza";
$this->dough = "Thin Crust Dough";
$this->sauce = "Marinara Sauce";

$this->toppings[] = "Grated Reggiano Cheese";
}
}

class NYStyleVeggiePizza extends Pizza {
public function __construct() {
$this->name = "NY Style Sauce and veggie Pizza";
$this->dough = "Thin Crust Dough";
$this->sauce = "Marinara Sauce";

$this->toppings[] = "Grated Reggiano veggie";
}
}
class NYStyleClamPizza extends Pizza {
public function __construct() {
$this->name = "NY Style Sauce and clam Pizza";
$this->dough = "Thin Crust Dough";
$this->sauce = "Marinara Sauce";

$this->toppings[] = "Grated Reggiano clam";
}
}
class NYStylePapperoniPizza extends Pizza {
public function __construct() {
$this->name = "NY Style Sauce and papperoni Pizza";
$this->dough = "Thin Crust Dough";
$this->sauce = "Marinara Sauce";

$this->toppings[] = "Grated Reggiano papperoni";
}
}

class ChicagoStyleCheesePizza extends Pizza {
public function __construct() {
$this->name = "Chicago Style Deep Dish Cheese Pizza";
$this->dough = "Extra Thick Crust Dough";
$this->sauce = "Plum Tomato Sauce";

$this->toppings[] = "Shredded Mozzarella Cheese";
}

public function cut() {
echo "Cutting the pizza into square slices\n";
}
}

$myStore = new NYPizzaStore();
$chicagoStore = new ChicagoPizzaStore();
$pizza = $myStore->orderPizza("cheese");
echo "Ethan ordered a " . $pizza->getName() . "\n";

$pizza = $chicagoStore->orderPizza("cheese");
echo "Ethan ordered a " . $pizza->getName() . "\n";

?>

工厂模式

复制代码 代码如下:

<?php
abstract class PizzaStore {
public function orderPizza($type) {
$pizza = $this->createPizza($type);

$pizza->prepare();
$pizza->bake();
$pizza->cut();
$pizza->box();
return $pizza;
}

public abstract function createPizza($type);
}
class NYPizzaStore extends PizzaStore {
public function createPizza($type) {
$pizza = null;
$ingredientFactory = new NYPizzaIngredientFactory();
if ($type == "cheese") {
$pizza = new CheesePizza($ingredientFactory);
$pizza->setName('New York Style Cheese Pizza');
} elseif ($type == "veggie") {
$pizza = new VeggiePizza($ingredientFactory);
$pizza->setName('New York Style Veggie Pizza');
} elseif ($type == "clam") {
$pizza = new ClamPizza($ingredientFactory);
$pizza->setName('New York Style Clam Pizza');
} elseif ($type == "papperoni") {
$pizza = new PapperoniPizza($ingredientFactory);
$pizza->setName('New York Style Papperoni Pizza');
}
return $pizza;
}
}
class ChicagoPizzaStore extends PizzaStore {
public function createPizza($type) {
if ($type == "cheese") {
return new ChicagoStyleCheesePizza();
} elseif ($type == "veggie") {
return new ChicagoStyleVeggiePizza();
} elseif ($type == "clam") {
return new ChicagoStyleClamPizza();
} elseif ($type == "papperoni") {
return new ChicagoStylePapperoniPizza();
} else {
return null;
}
}
}
interface PizzaIngredientFactory {
public function createDough();
public function createSauce();
public function createCheese();
public function createVeggies();
public function createPepperoni();
public function createClam();
}
class NYPizzaIngredientFactory implements PizzaIngredientFactory {
public function createDough() {
return new ThinCrustDough();
}
public function createSauce() {
return new MarinaraSauce();
}
public function createCheese() {
return new ReggianoCheese();
}
public function createVeggies() {
$veggies = array(
new Garlic(),
new Onion(),
new Mushroom(),
new RedPepper(),
);
return $veggies;
}
public function createPepperoni() {
return new SlicedPepperoni();
}
public function createClam() {
return new FreshClams();
}
}
class ChicagoPizzaIngredientFactory implements PizzaIngredientFactory {
public function createDough() {
return new ThickCrustDough();
}
public function createSauce() {
return new PlumTomatoSauce();
}
public function createCheese() {
return new Mozzarella();
}
public function createVeggies() {
$veggies = array(
new BlackOlives(),
new Spinach(),
new EggPlant(),
);
return $veggies;
}
public function createPepperoni() {
return new SlicedPepperoni();
}
public function createClam() {
return new FrozenClams();
}
}
abstract class Pizza {
public $name;
public $dough;
public $sauce;
public $veggies = array();
public $cheese;
public $pepperoni;
public $clam;

public abstract function prepare();

public function bake() {
echo "Bake for 25 minutes at 350\n";
}

public function cut() {
echo "Cutting the pizza into diagonal slices\n";
}

public function box() {
echo "Place pizza in official PizzaStore box\n";
}

public function getName() {
return $this->name;
}

public function setName($name) {
$this->name = $name;
}

public function __toString() {

}
}

class CheesePizza extends Pizza {
public $ingredientFactory;

public function __construct(PizzaIngredientFactory $ingredientFactory) {
$this->ingredientFactory = $ingredientFactory;
}

public function prepare() {
echo "Preparing " . $this->name . "\n";
$this->dough = $this->ingredientFactory->createDough();
$this->sauce = $this->ingredientFactory->createSauce();
$this->cheese = $this->ingredientFactory->createCheese();
}
}

class ClamPizza extends Pizza {
public $ingredientFactory;

public function __construct(PizzaIngredientFactory $ingredientFactory) {
$this->ingredientFactory = $ingredientFactory;
}

public function prepare() {
echo "Preparing " . $this->name . "\n";
$this->dough = $this->ingredientFactory->createDough();
$this->sauce = $this->ingredientFactory->createSauce();
$this->cheese = $this->ingredientFactory->createCheese();
$clam = $this->ingredientFactory->createClam();
}
}

$nyPizzaStore = new NYPizzaStore();
$nyPizzaStore->orderPizza('cheese');
?>

当前1/2页 12下一页阅读全文

时间: 2024-10-02 05:56:49

《Head First 设计模式》代码之PHP版(面向对象学习)第1/2页_php技巧的相关文章

php开发分页实现代码第1/3页_php技巧

项目结构: 开发分页实现代码第1/3页_php技巧-mybatis实现分页查询"> 运行效果: conn.php 复制代码 代码如下: <?php $conn = @ mysql_connect("localhost", "root", "") or die("数据库链接错误"); mysql_select_db("form", $conn); mysql_query("se

PHP版微信小店接口开发实例_php技巧

本文实例讲述了PHP版微信小店接口开发方法.分享给大家供大家参考,具体如下: 首先 大家可以去下一份小店开发的 API接口 因为 下面所有的 微信小店接口 数据格式 参数 API手册 里面都有现成的 你可以直接拿来用 好了 下面上代码 这里给大家 下载微小店 API文档 这里就先拿查询商品作为例子 //首先第一步是 获取access_token的代码 我这里呢 对token做了存表里的 因为token有限制 private function access_token(){ appid=shopa

php学习 面向对象 课件第1/2页_php基础

  对象的主要三个特性 对象的行为:可以对 对象施加那些操作,开灯,关灯就是行为. 对象的形态:当施加那些方法是对象如何响应,颜色,尺寸,外型. 对象的表示:对象的表示就相当于身份证,具体区分在相同的行为与状态下有什么不同.     面向对象模型 面向对象的概念: oop(面向对象的编程)它能是其代码更加简洁易于维护并且具有更强的可重性 什么是类: 类是具有相同属性和服务的一组对象的集合比如说人,书,轮船,车都属于类,他为属于该类的对象做了一个统一的抽象描述,在编程的语言中类是一个单独的程序,它

PHP面向对象分析设计的经验原则_php技巧

(1)所有数据都应该隐藏在所在的类的内部. (2)类的使用者必须依赖类的共有接口,但类不能依赖它的使用者. (3)尽量减少类的协议中的消息. (4)实现所有类都理解的最基本公有接口[例如,拷贝操作(深拷贝和浅拷贝).相等性判断.正确输出内容.从ASCII描述解析等等]. (5)不要把实现细节(例如放置共用代码的私有函数)放到类的公有接口中. 如果类的两个方法有一段公共代码,那么就可以创建一个防止这些公共代码的私有函数. (6)不要以用户无法使用或不感兴趣的东西扰乱类的公有接口. (7)类之间应该

PHP程序61条面向对象分析设计的经验小结_php技巧

(1)所有数据都应该隐藏在所在的类的内部. (2)类的使用者必须依赖类的共有接口,但类不能依赖它的使用者. (3)尽量减少类的协议中的消息. (4)实现所有类都理解的最基本公有接口[例如,拷贝操作(深拷贝和浅拷贝).相等性判断.正确输出内容.从ASCII描述解析等等]. (5)不要把实现细节(例如放置共用代码的私有函数)放到类的公有接口中. 如果类的两个方法有一段公共代码,那么就可以创建一个防止这些公共代码的私有函数. (6)不要以用户无法使用或不感兴趣的东西扰乱类的公有接口. (7)类之间应该

PHP7正式版测试,性能惊艳!_php技巧

我们今天就来看一下PHP 7正式版的算法和 wordpress 应用在其上的性能表现. PHP7 的安装,真是非常地向下兼容,下载,解压,把之前的配置命令用上,一路回车下去,毫无违和感.为了不影响现有的环境的运行,所有专门开辟了目录 . 配置参数如下: --prefix=/usr/local/php7 --with-config-file-path=/usr/local/php7/etc --enable-fpm --with-fpm-user=www --with-fpm-group=www

php代码出现错误分析详解第1/2页_php技巧

错误类型: 一.未使用二进制上传   代码:    Fatal error: This encoded file is corrupted. Please refer to http://www.zend.com/support/support_faq.php?id=loader_file_corrupt for further help in  /webhome/****.com/web/www/index.php on line 0  二.数据表中缺少字段   代码:    An error

Discuz5.5.0代码高亮显示+运行代码框合成插件 下载第1/4页_php技巧

主要功能: 1.几乎支持所有程序代码的高亮显示,包括以下语言:Actionscript.ADA.Apache Log.AppleScript.ASM.ASP.AutoIT.Backus-Naur form.Bash.BlitzBasic.C.C for Macs.C#.C++.CAD DCL.CadLisp.CFDG.CFDG.ColdFusion.CSS.Delphi.DIV.DOS.Eiffel.Fortran.Fortran.FreeBasic.GML.Groovy.HTML.Inno.I

php xml分析函数代码第1/2页_php技巧

首先我得承认我喜欢计算机标准.如果每个人都遵从这个行业的标准,互联网将会是一个更好的媒体.使用标准化的数据交换格式才能使开放的和独立于平台的计算模式切实可行.这就是我作为XML爱好者的原因. 幸运的是,我最喜爱的脚本语言不但支持XML而且对其支持正不断加强.PHP可以让我迅速将XML文档发布到互联网上,收集XML文档的统计信息,将XML文档转换成其它格式.例如,我时常用PHP的XML处理能力来管理我用XML所写的文章和书. 本文中,我将讨论任何用PHP内建的Expat解析器来处理XML文档.通过