`
aslijiasheng
  • 浏览: 58381 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

设计模式

    博客分类:
  • php
 
阅读更多

Design Patterns

There are numerous ways to structure the code and project for you web application, and you can put as much or as little thought as you like into architecting. But it is usually a good idea to follow common patterns because it will make your code easier to manage and easier for others to understand.

Factory

One of the most commonly used design patterns is the factory pattern. In this pattern, a class simply creates the object you want to use. Consider the following example of the factory pattern:

<?php
class Automobile
{
    private $vehicle_make;
    private $vehicle_model;

    public function __construct($make, $model)
    {
        $this->vehicle_make = $make;
        $this->vehicle_model = $model;
    }

    public function get_make_and_model()
    {
        return $this->vehicle_make . ' ' . $this->vehicle_model;
    }
}

class AutomobileFactory
{
    public static function create($make, $model)
    {
        return new Automobile($make, $model);
    }
}

// have the factory create the Automobile object
$veyron = AutomobileFactory::create('Bugatti', 'Veyron');

print_r($veyron->get_make_and_model()); // outputs "Bugatti Veyron"

This code uses a factory to create the Automobile object. There are two possible benefits to building your code this way; the first is that if you need to change, rename, or replace the Automobile class later on you can do so and you will only have to modify the code in the factory, instead of every place in your project that uses the Automobile class. The second possible benefit is that if creating the object is a complicated job you can do all of the work in the factory, instead of repeating it every time you want to create a new instance.

Using the factory pattern isn’t always necessary (or wise). The example code used here is so simple that a factory would simply be adding unneeded complexity. However if you are making a fairly large or complex project you may save yourself a lot of trouble down the road by using factories.

Singleton

When designing web applications, it often makes sense conceptually and architecturally to allow access to one and only one instance of a particular class. The singleton pattern enables us to do this.

<?php
class Singleton
{
    /**
     * Returns the *Singleton* instance of this class.
     *
     * @staticvar Singleton $instance The *Singleton* instances of this class.
     *
     * @return Singleton The *Singleton* instance.
     */
    public static function getInstance()
    {
        static $instance = null;
        if (null === $instance) {
            $instance = new static();
        }

        return $instance;
    }

    /**
     * Protected constructor to prevent creating a new instance of the
     * *Singleton* via the `new` operator from outside of this class.
     */
    protected function __construct()
    {
    }

    /**
     * Private clone method to prevent cloning of the instance of the
     * *Singleton* instance.
     *
     * @return void
     */
    private function __clone()
    {
    }

    /**
     * Private unserialize method to prevent unserializing of the *Singleton*
     * instance.
     *
     * @return void
     */
    private function __wakeup()
    {
    }
}

class SingletonChild extends Singleton
{
}

$obj = Singleton::getInstance();
var_dump($obj === Singleton::getInstance());             // bool(true)

$anotherObj = SingletonChild::getInstance();
var_dump($anotherObj === Singleton::getInstance());      // bool(false)

var_dump($anotherObj === SingletonChild::getInstance()); // bool(true)

The code above implements the singleton pattern using a static variable and the static creation method getInstance(). Note the following:

  • The constructor __construct is declared as protected to prevent creating a new instance outside of the class via the new operator.
  • The magic method __clone is declared as private to prevent cloning of an instance of the class via the clone operator.
  • The magic method __wakeup is declared as private to prevent unserializing of an instance of the class via the global function unserialize().
  • A new instance is created via late static binding in the static creation method getInstance() with the keyword static. This allows the subclassing of the class Singleton in the example.

The singleton pattern is useful when we need to make sure we only have a single instance of a class for the entire request lifecycle in a web application. This typically occurs when we have global objects (such as a Configuration class) or a shared resource (such as an event queue).

You should be wary when using the singleton pattern, as by its very nature it introduces global state into your application, reducing testability. In most cases, dependency injection can (and should) be used in place of a singleton class. Using dependency injection means that we do not introduce unnecessary coupling into the design of our application, as the object using the shared or global resource requires no knowledge of a concretely defined class.

Strategy

With the strategy pattern you encapsulate specific families of algorithms allowing the client class responsible for instantiating a particular algorithm to have no knowledge of the actual implementation. There are several variations on the strategy pattern, the simplest of which is outlined below:

This first code snippet outlines a family of algorithms; you may want a serialized array, some JSON or maybe just an array of data:

<?php

interface OutputInterface
{
    public function load();
}

class SerializedArrayOutput implements OutputInterface
{
    public function load()
    {
        return serialize($arrayOfData);
    }
}

class JsonStringOutput implements OutputInterface
{
    public function load()
    {
        return json_encode($arrayOfData);
    }
}

class ArrayOutput implements OutputInterface
{
    public function load()
    {
        return $arrayOfData;
    }
}

By encapsulating the above algorithms you are making it nice and clear in your code that other developers can easily add new output types without affecting the client code.

You will see how each concrete ‘output’ class implements an OutputInterface - this serves two purposes, primarily it provides a simple contract which must be obeyed by any new concrete implementations. Secondly by implementing a common interface you will see in the next section that you can now utilise Type Hinting to ensure that the client which is utilising these behaviours is of the correct type in this case ‘OutputInterface’.

The next snippet of code outlines how a calling client class might use one of these algorithms and even better set the behaviour required at runtime:

<?php

class SomeClient
{
    private $output;

    public function setOutput(OutputInterface $outputType)
    {
        $this->output = $outputType;
    }

    public function loadOutput()
    {
        return $this->output->load();
    }
}

The calling client class above has a private property which must be set at runtime and be of type ‘OutputInterface’ once this property is set a call to loadOutput() will call the load() method in the concrete class of the output type that has been set.

<?php

$client = new SomeClient();

// Want an array?
$client->setOutput(new ArrayOutput());
$data = $client->loadOutput();

// Want some JSON?
$client->setOutput(new JsonStringOutput());
$data = $client->loadOutput();

Front Controller

The front controller pattern is where you have a single entrance point for you web application (e.g. index.php) that handles all of the requests. This code is responsible for loading all of the dependencies, processing the request and sending the response to the browser. The front controller pattern can be beneficial because it encourages modular code and gives you a central place to hook in code that should be run for every request (such as input sanitization).

Model-View-Controller

The model-view-controller (MVC) pattern and its relatives HMVC and MVVM lets you break up code into logical objects that serve very specific purposes. Models serve as a data access layer where data is fetched and returned in formats usable throughout your application. Controllers handle the request, process the data returned from models and load views to send in the response. And views are display templates (markup, xml, etc) that are sent in the response to the web browser.

MVC is the most common architectural pattern used in the popular PHP frameworks.

Learn more about MVC and its relatives:

分享到:
评论

相关推荐

    24种设计模式以及混合设计模式

    设计模式是软件工程中的一种重要思想,它是在特定情境下,为解决常见问题而形成的一套最佳实践。在本文中,我们将深入探讨24种设计模式,并结合混合设计模式的概念,以及它们在实际项目中的应用案例。 首先,设计...

    人人都懂设计模式 人人都懂设计模式

    人人都懂设计模式 设计模式是软件开发中的一种解决方案,它提供了一种通用的设计思想和方法论,可以帮助开发者更好地设计和实现软件系统。设计模式可以分为三大类:创建型模式、结构型模式和行为型模式。 在本书中...

    二十三种设计模式【PDF版】

    主要是介绍各种格式流行的软件设计模式,对于程序员的进一步提升起推进作用,有时间可以随便翻翻~~ 23种设计模式汇集 如果你还不了解设计模式是什么的话? 那就先看设计模式引言 ! 学习 GoF 设计模式的重要性 ...

    23种设计模式详解PDF

    设计模式 的分类 总体来说设计模式分为三大类: 创建型模式(5): 工厂方法模式 、抽象工厂模式、单例模式、建造者模式、原型模式。 结构型模式(7): 适配器模式、装饰器模式、代理模式、外观模式、桥接模式、...

    GOF设计模式中英文+设计模式精解中英文

    GOF(Gang of Four)设计模式,由Erich Gamma、Richard Helm、Ralph Johnson和John Vlissides四位专家在他们的著作《设计模式:可复用面向对象软件的基础》中提出,被誉为设计模式的经典之作。本资源包含了GOF设计...

    Head First 设计模式 +Java设计模式(第2版)

    《Head First 设计模式》与《Java设计模式(第2版)》是两本非常重要的IT书籍,专注于软件开发中的设计模式。设计模式是解决软件设计中常见问题的经验总结,它们提供了一种标准的方法来处理特定场景下的问题,使得代码...

    C#设计模式.PDF

    根据提供的文档概览,我们可以对每个章节所涉及的设计模式进行详细的阐述和解释。下面将针对文档中提及的设计模式逐一展开,以便更好地理解这些模式的概念、结构、应用场景以及优缺点。 ### 1. 面向对象程序设计...

    设计模式(包含5个设计模式)含源代码报告.rar

    这个压缩包文件"设计模式(包含5个设计模式)含源代码报告.rar"显然是一份宝贵的资源,它涵盖了五个核心的设计模式,并附带了详细的类图、源代码以及文档报告,这对于学习和理解设计模式至关重要。 首先,我们要探讨...

    设计模式之蝉

    在计算机科学领域,设计模式是软件工程中用于解决特定问题的一般性方案,它们是经过实践检验的最佳实践。这些模式被广泛应用于面向对象软件设计中,能够提高代码的可重用性、灵活性和可维护性。设计模式通常被划分为...

    python设计模式第2版.pdf

    设计模式是构建大型软件系统zui强大的方法之一,优化软件架构和设计已经逐渐成为软件开发和维护过程中的一个重要课题。 Python设计模式(第2版)通过11章内容,全面揭示有关设计模式的内容,并结合Python语言进行示例...

    软件设计模式大作业

    软件设计模式大作业 本资源为一份完整的软件设计模式大作业,涵盖了六种设计模式的应用,分别是简单工厂模式、工厂方法模式、单例模式、门面模式、策略模式和观察者模式。该大作业的主要内容包括系统流程、系统类图...

    《Java设计模式》课程设计报告.docx

    《Java设计模式》课程设计报告主要探讨了如何利用Java编程语言和MyEclipse集成开发环境来实现基于设计模式的西瓜市场系统。这个项目涵盖了四种重要的设计模式:单例模式、代理模式、建造者模式和抽象工厂模式,为...

    新版设计模式手册 - C#设计模式(第二版)

    《新版设计模式手册 - C#设计模式(第二版)》是一部深入探讨C#编程中设计模式的权威指南,尤其适合已经有一定C#基础并希望提升软件设计能力的开发者阅读。设计模式是解决软件开发中常见问题的经验总结,是软件工程的...

    软件设计模式(java版)习题答案.pdf

    软件设计模式(Java版)习题答案 本资源为软件设计模式(Java版)习题答案,由程细柱编著,人民邮电出版社出版。该资源涵盖了软件设计模式的基础知识,包括软件设计模式的概述、UML中的类图、面向对象的设计原则、...

    设计模式精解- GoF 23种设计模式解析附C++实现源码

    设计模式精解- GoF 23种设计模式解析附C++实现源码 懂了设计模式,你就懂了面向对象分析和设计(OOA/D)的精要。反之好像也可能成立。道可道,非常道。道不远人,设计模式亦然如此。 一直想把自己的学习经验以及在...

    C_设计模式(23种设计模式)

    C_设计模式(23种设计模式)C_设计模式(23种设计模式)C_设计模式(23种设计模式)C_设计模式(23种设计模式)C_设计模式(23种设计模式)C_设计模式(23种设计模式)C_设计模式(23种设计模式)C_设计模式(23种设计模式)C_设计...

    Head First设计模式.pdf

    全书用两章篇幅对设计模式和GRASP作了基本介绍,3种设计模式的讲解:对于每一种模式,先给出定义,接着通过类比方式用一个现实世界中的例子说明模式的应用,然后分别以C#和Java代码例述模式的架构实现。最后一章给出...

    MongoDB应用设计模式

    资源名称:MongoDB应用设计模式内容简介:无论是在构建社交媒体网站,还是在开发一个仅在内部使用的企业应用程序,《MongoDB应用设计模式》展示了MongoDB需要解决的商业问题之间的连接。你将学到如何把MongoDB设计...

    设计模式那点事

    设计模式是软件工程中的一种重要概念,它代表了在特定情境下解决问题的可重用解决方案。《设计模式那点事》这本书的PPT为我们提供了一种深入理解和学习设计模式的途径。在这里,我们将深入探讨设计模式的核心概念、...

Global site tag (gtag.js) - Google Analytics