《Head First 设计模式》是本不错的讲解设计模式的书,不像F4写的那么枯燥,应该算是比较容易理解的好书。
书中的例子都比较浅显易懂,不过由于是外国佬写的,所以例子的习惯不是很附合中国特色,可能偶尔看起来有些别扭,还有语言习惯也不是中国风。当然��看过这本书之后,你才能深刻理解设计模式到底能为你解决哪些问题,不能为你解决哪些问题(比如不能代替你的编码)。
我将书中部分代码改成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'); ?>
观察者模式
代码如下:
<?php /** * 观察者模式 * 定义了对象之间的一对多依赖,当一个对象改变状态时, * 它的所有依赖者都会收到通知并自动更新。 */ interface Subject { public function registerObserver(Observer $o); public function removeObserver(Observer $o); public function notifyObservers(); } interface Observer { public function update($temperature, $humidity, $pressure); } interface DisplayElement { public function display(); } class WeatherData implements Subject { private $observers = array(); private $temperature; private $humidity; private $pressure; public function __construct() { $this->observers = array(); } public function registerObserver(Observer $o) { $this->observers[] = $o; } public function removeObserver(Observer $o) { if (($key = array_search($o, $this->observers)) !== false) { unset($this->observers[$key]); } } public function notifyObservers() { foreach ($this->observers as $observer) { $observer->update($this->temperature, $this->humidity, $this->pressure); } } public function measurementsChanged() { $this->notifyObservers(); } public function setMeasurements($temperature, $humidity, $pressure) { $this->temperature = $temperature; $this->humidity = $humidity; $this->pressure = $pressure; $this->measurementsChanged(); } } class CurrentConditionsDisplay implements Observer, DisplayElement { private $temperature; private $humidity; private $weatherData; public function __construct(Subject $weatherData) { $this->weatherData = $weatherData; $weatherData->registerObserver($this); } public function update($temperature, $humidity, $pressure) { $this->temperature = $temperature; $this->humidity = $humidity; $this->display(); } public function display() { echo "温度:" . $this->temperature . "; 湿度:" . $this->humidity . "%\n"; } } class StatistionsDisplay implements Observer, DisplayElement { private $temperature; private $humidity; private $pressure; private $weatherData; public function __construct(Subject $weatherData) { $this->weatherData = $weatherData; $weatherData->registerObserver($this); } public function update($temperature, $humidity, $pressure) { $this->temperature = $temperature; $this->humidity = $humidity; $this->pressure = $pressure; $this->display(); } public function display() { echo "温度:" . $this->temperature . "; 湿度:" . $this->humidity . "%; 气压:" . $this->pressure . "\n"; } } $weatherData = new WeatherData(); $currentDisplay = new CurrentConditionsDisplay($weatherData); $statistionDisplay = new StatistionsDisplay($weatherData); $weatherData->setMeasurements(10, 20, 30); $weatherData->removeObserver($currentDisplay); $weatherData->setMeasurements(30, 40, 50); ?>
命令模式
复制代码 代码如下:
<?php class Light { public function __construct() { } public function on() { echo "Light On\n"; } public function off() { echo "Light Off\n"; } } interface Command { public function execute(); } class LightOnCommand implements Command { public $light; public function __construct(Light $light) { $this->light = $light; } public function execute() { $this->light->on(); } } class SimpleRemoteControl { public $slot; public function __construct() { } public function setCommand(Command $command) { $this->slot = $command; } public function buttonWasPressed() { $this->slot->execute(); } } class RemoteControlTest { public static function main() { $remote = new SimpleRemoteControl(); $light = new Light(); $lightOn = new LightOnCommand($light); $remote->setCommand($lightOn); $remote->buttonWasPressed(); } } RemoteControlTest::main(); ?>
装饰者模式
复制代码 代码如下:
<?php /** * 装饰着模式 * 动态地将责任附加到对象上,若要扩展功能,装饰者提供了比继承更有弹性的替代方案。 */ abstract class Beverage { public $description = "Unknown Beverage"; public function getDescription() { return $this->description; } public abstract function cost(); } abstract class CondimentDecorator extends Beverage { //JAVA代码里这里是个抽象类,PHP不允许这么做 public function getDescription() { return $this->description; } } class Espresso extends Beverage { public function __construct() { $this->description = "Espresso"; } public function cost() { return 1.99; } } class HouseBlend extends Beverage { public function __construct() { $this->description = "HouseBlend"; } public function cost() { return .89; } } class DarkRoast extends Beverage { public function __construct() { $this->description = "DarkRoast"; } public function cost() { return .99; } } class Mocha extends CondimentDecorator { public $beverage; public function __construct(Beverage $beverage) { $this->beverage = $beverage; } public function getDescription() { return $this->beverage->getDescription() . ", Mocha"; } public function cost() { return .20 + $this->beverage->cost(); } } class Whip extends CondimentDecorator { public $beverage; public function __construct(Beverage $beverage) { $this->beverage = $beverage; } public function getDescription() { return $this->beverage->getDescription() . ", Whip"; } public function cost() { return .10 + $this->beverage->cost(); } } class Soy extends CondimentDecorator { public $beverage; public function __construct(Beverage $beverage) { $this->beverage = $beverage; } public function getDescription() { return $this->beverage->getDescription() . ", Soy"; } public function cost() { return .15 + $this->beverage->cost(); } } $beverage = new Espresso(); echo $beverage->getDescription() . "\n"; $beverage2 = new DarkRoast(); $beverage2 = new Mocha($beverage2); $beverage2 = new Mocha($beverage2); $beverage2 = new Whip($beverage2); echo $beverage2->getDescription() . " $" . $beverage2->cost() . "\n"; $beverage3 = new HouseBlend(); $beverage3 = new Soy($beverage3); $beverage3 = new Mocha($beverage3); $beverage3 = new Whip($beverage3); echo $beverage3->getDescription() . " $" . $beverage3->cost() . "\n"; ?>
状态模式
复制代码 代码如下:
<?php class GumballMachine { const SOLD_OUT = 0; const NO_QUARTER = 1; const HAS_QUARTER = 2; const SOLD = 3; public $state = self::SOLD_OUT; public $count = 0; public function __construct($count) { $this->count = $count; if ($count > 0) { $this->state = self::NO_QUARTER; } } public function insertQuarter() { if ($this->state == self::HAS_QUARTER) { echo "You can't insert another quarter!\n"; } else if ($this->state == self::NO_QUARTER) { $this->state = self::HAS_QUARTER; echo "You inserted a quarter!\n"; } else if ($this->state == self::SOLD_OUT) { echo "You can't insert a quarter, the machine is sold out!\n"; } else if ($this->state == self::SOLD) { echo "Please wait, we're already giving you a gumball!\n"; } } } $obj = new GumballMachine(0); print_r($obj) ?>
以上就是《Head First 设计模式》代码之PHP版(面向对象学习)_php技巧的内容,更多相关内容请关注PHP中文网(www.php.cn)!

PHP는 전자 상거래, 컨텐츠 관리 시스템 및 API 개발에 널리 사용됩니다. 1) 전자 상거래 : 쇼핑 카트 기능 및 지불 처리에 사용됩니다. 2) 컨텐츠 관리 시스템 : 동적 컨텐츠 생성 및 사용자 관리에 사용됩니다. 3) API 개발 : 편안한 API 개발 및 API 보안에 사용됩니다. 성능 최적화 및 모범 사례를 통해 PHP 애플리케이션의 효율성과 유지 보수 성이 향상됩니다.

PHP를 사용하면 대화식 웹 컨텐츠를 쉽게 만들 수 있습니다. 1) HTML을 포함하여 컨텐츠를 동적으로 생성하고 사용자 입력 또는 데이터베이스 데이터를 기반으로 실시간으로 표시합니다. 2) 프로세스 양식 제출 및 동적 출력을 생성하여 htmlspecialchars를 사용하여 XSS를 방지합니다. 3) MySQL을 사용하여 사용자 등록 시스템을 작성하고 Password_Hash 및 전처리 명세서를 사용하여 보안을 향상시킵니다. 이러한 기술을 마스터하면 웹 개발의 효율성이 향상됩니다.

PHP와 Python은 각각 고유 한 장점이 있으며 프로젝트 요구 사항에 따라 선택합니다. 1.PHP는 웹 개발, 특히 웹 사이트의 빠른 개발 및 유지 보수에 적합합니다. 2. Python은 간결한 구문을 가진 데이터 과학, 기계 학습 및 인공 지능에 적합하며 초보자에게 적합합니다.

PHP는 여전히 역동적이며 현대 프로그래밍 분야에서 여전히 중요한 위치를 차지하고 있습니다. 1) PHP의 단순성과 강력한 커뮤니티 지원으로 인해 웹 개발에 널리 사용됩니다. 2) 유연성과 안정성은 웹 양식, 데이터베이스 작업 및 파일 처리를 처리하는 데 탁월합니다. 3) PHP는 지속적으로 발전하고 최적화하며 초보자 및 숙련 된 개발자에게 적합합니다.

PHP는 현대 웹 개발, 특히 컨텐츠 관리 및 전자 상거래 플랫폼에서 중요합니다. 1) PHP는 Laravel 및 Symfony와 같은 풍부한 생태계와 강력한 프레임 워크 지원을 가지고 있습니다. 2) Opcache 및 Nginx를 통해 성능 최적화를 달성 할 수 있습니다. 3) PHP8.0은 성능을 향상시키기 위해 JIT 컴파일러를 소개합니다. 4) 클라우드 네이티브 애플리케이션은 Docker 및 Kubernetes를 통해 배포되어 유연성과 확장 성을 향상시킵니다.

PHP는 특히 빠른 개발 및 동적 컨텐츠를 처리하는 데 웹 개발에 적합하지만 데이터 과학 및 엔터프라이즈 수준의 애플리케이션에는 적합하지 않습니다. Python과 비교할 때 PHP는 웹 개발에 더 많은 장점이 있지만 데이터 과학 분야에서는 Python만큼 좋지 않습니다. Java와 비교할 때 PHP는 엔터프라이즈 레벨 애플리케이션에서 더 나빠지지만 웹 개발에서는 더 유연합니다. JavaScript와 비교할 때 PHP는 백엔드 개발에서 더 간결하지만 프론트 엔드 개발에서는 JavaScript만큼 좋지 않습니다.

PHP와 Python은 각각 고유 한 장점이 있으며 다양한 시나리오에 적합합니다. 1.PHP는 웹 개발에 적합하며 내장 웹 서버 및 풍부한 기능 라이브러리를 제공합니다. 2. Python은 간결한 구문과 강력한 표준 라이브러리가있는 데이터 과학 및 기계 학습에 적합합니다. 선택할 때 프로젝트 요구 사항에 따라 결정해야합니다.

PHP는 서버 측에서 널리 사용되는 스크립팅 언어이며 특히 웹 개발에 적합합니다. 1.PHP는 HTML을 포함하고 HTTP 요청 및 응답을 처리 할 수 있으며 다양한 데이터베이스를 지원할 수 있습니다. 2.PHP는 강력한 커뮤니티 지원 및 오픈 소스 리소스를 통해 동적 웹 컨텐츠, 프로세스 양식 데이터, 액세스 데이터베이스 등을 생성하는 데 사용됩니다. 3. PHP는 해석 된 언어이며, 실행 프로세스에는 어휘 분석, 문법 분석, 편집 및 실행이 포함됩니다. 4. PHP는 사용자 등록 시스템과 같은 고급 응용 프로그램을 위해 MySQL과 결합 할 수 있습니다. 5. PHP를 디버깅 할 때 error_reporting () 및 var_dump ()와 같은 함수를 사용할 수 있습니다. 6. 캐싱 메커니즘을 사용하여 PHP 코드를 최적화하고 데이터베이스 쿼리를 최적화하며 내장 기능을 사용하십시오. 7


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

드림위버 CS6
시각적 웹 개발 도구

WebStorm Mac 버전
유용한 JavaScript 개발 도구

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경
