Table of Contents
PHP设计模式——抽象工厂
Home php教程 php手册 PHP设计模式抽象工厂

PHP设计模式抽象工厂

Jun 13, 2016 am 09:06 AM
factory Design Patterns

PHP设计模式——抽象工厂

 

前面我们介绍了简单工厂和工厂方法设计模式,今天我们学习最后一个工厂——抽象工厂。

 

 

案例:追MM少不了请吃饭了,去麦当劳,只管向服务员说“两个B套餐”就行了。麦当劳就是B套餐的AbstractFactory,B套餐里含有汉堡, 鸡翅和饮料. 麦当劳或肯德基会根据B套餐的规格, 让汉堡Factory, 鸡翅Factory,饮料Factory分别生产对应B套餐的材料.

抽象工厂模式:提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。客户类和工厂类分开。消费者任何时候需要某套产品集合时,只需向抽象工厂请求即可。抽象工厂会再向具体的工厂生产出符合产品集规格的产品.

 

UML类图实现:

 

UML类图代码实现:

 

<!--?php
/**
 * Created by PhpStorm.
 * User: LYL
 * Date: 2015/4/19
 * Time: 17:39
 */

//-----------------------产品------------------------

/**抽象产品角色             充饥食物
 * Interface IAllayFood
 */
interface IAllayFood
{
    function Allay();
}

/**抽象产品角色            解渴食物
 * Interface IDrinkFood
 */
interface IDrinkFood
{
    function Drink();
}

/**具体产品角色           虾仁汉堡
 * Class XiaRenHamb
 */
class XiaRenHamb implements IAllayFood
{
    function Allay()
    {
        echo 虾仁汉堡充饥了。。。。。。。<br/-->;
    }
}

/**具体产品角色            鸡肉汉堡
 * Class ChickenHamb
 */
class ChickenHamb implements IAllayFood
{
    function Allay()
    {
        echo 鸡肉汉堡充饥了。。。。。。。
;
    }
}

/**具体产品角色             可口可乐
 * Class KekouKele
 */
class KekouKele implements IDrinkFood
{

    function Drink()
    {
        echo 可口可乐解渴了。。。。。。。。。
;
    }
}

/**具体产品角色             百事可乐
 * Class BaishiKele
 */
class BaishiKele implements IDrinkFood
{

    function Drink()
    {
        echo 百事可乐解渴了。。。。。。。。
;
    }
}

//-------------------抽象工厂---------------------

/**顶层超级抽象工厂接口
 * Interface IFactory
 */
interface IFactory
{
    //得到充饥食物
    function GetAllayFood();
    //得到解渴食物
    function GetDrinkFood();
}

/**工厂A              A套餐:虾仁汉堡+百事可乐
 * Class IAFactory
 */
class AFactory implements IFactory
{

    function GetAllayFood()
    {
        return new XiaRenHamb();
    }

    function GetDrinkFood()
    {
        return new BaishiKele();
    }
}

/**工厂B                B套餐:鸡肉汉堡+可口可乐
 * Class IBFactory
 */
class BFactory implements IFactory
{

    function GetAllayFood()
    {
        return new ChickenHamb();
    }

    function GetDrinkFood()
    {
        return new KekouKele();
    }
}
Copy after login

客户端测试代码

header(Content-Type:text/html;charset=utf-8);
//------------------------抽象工厂测试代码------------------
require_once ./AbstractFactory/AbstractFactory.php;

//------------------点套餐-------------
$factoryA=new AFactory();
$factoryB=new BFactory();

//------------------麦当劳制作套餐食物------------
//A套餐
$allayA=$factoryA->GetAllayFood();
$drinkA=$factoryA->GetDrinkFood();

//B套餐
$allayB=$factoryB->GetAllayFood();
$drinkB=$factoryB->GetDrinkFood();

//-------------------享受套餐---------------
echo 享受A套餐:
;
$allayA->Allay();
$drinkA->Drink();

echo 享受B套餐:
;
$allayB->Allay();
$drinkB->Drink();
Copy after login

 

当每个抽象产品都有多于一个的具体子类的时候,工厂角色怎么知道实例化哪一个子类呢?比如每个抽象产品角色都有两个具体产品。抽象工厂模式提供两个具体工厂角色,分别对应于这两个具体产品角色,每一个具体工厂角色只负责某一个产品角色的实例化。每一个具体工厂类只负责创建抽象产品的某一个具体子类的实例。

 

适用场景:

1、游戏开发中的多风格系列场景(套餐),比如道路(接口),房屋,管道等。

2、系统要在三个不同平台上运行,比如Windows、Linux、Android上运行,你会怎么设计?通过抽象工厂模式屏蔽掉操作系统对应用的影响。三个不同操作系统上的软件功能、应用逻辑、UI都应该是非常类似,唯一不同的是调用不同的工厂方法,由不同的产品类去处理与操作系统交互的信息。

3、需要创建的对象是一系列相互关联或相互依赖的产品族时,便可以使用抽象工厂模式。


三种工厂模式总结:

 

1.三种在形式和特点上极为相似,最终目的都是解耦。将对象的创建过程进行封装,使客户端可以直接得到对象,而不用去关心如何创建对象。

2.对比

工厂方法模式:用于创建复杂对象。(单点食物)

抽象工厂模式:用于创建一组相关或相互依赖的复杂对象。(买套餐)

工厂方法创建一般只有一个方法,创建一种产品。抽象工厂一般有多个方法,创建一系列产品。

 

我们不必去在意模式到底工厂方法模式还是抽象工厂模式,因为他们之间的演变常常是令人琢磨不透的。明明使用的工厂方法模式,当新需求来临,稍加修改,加入了一个新方法后,由于类中的产品构成了不同等级结构中的产品族,它就变成抽象工厂模式了,而对于抽象工厂模式,当减少一个方法使的提供的产品不再构成产品族之后,它就演变成了工厂方法模式。

 
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The difference between design patterns and architectural patterns in Java framework The difference between design patterns and architectural patterns in Java framework Jun 02, 2024 pm 12:59 PM

In the Java framework, the difference between design patterns and architectural patterns is that design patterns define abstract solutions to common problems in software design, focusing on the interaction between classes and objects, such as factory patterns. Architectural patterns define the relationship between system structures and modules, focusing on the organization and interaction of system components, such as layered architecture.

Analysis of the Decorator Pattern in Java Design Patterns Analysis of the Decorator Pattern in Java Design Patterns May 09, 2024 pm 03:12 PM

The decorator pattern is a structural design pattern that allows dynamic addition of object functionality without modifying the original class. It is implemented through the collaboration of abstract components, concrete components, abstract decorators and concrete decorators, and can flexibly expand class functions to meet changing needs. In this example, milk and mocha decorators are added to Espresso for a total price of $2.29, demonstrating the power of the decorator pattern in dynamically modifying the behavior of objects.

The wonderful use of the adapter pattern in Java design patterns The wonderful use of the adapter pattern in Java design patterns May 09, 2024 pm 12:54 PM

The Adapter pattern is a structural design pattern that allows incompatible objects to work together. It converts one interface into another so that the objects can interact smoothly. The object adapter implements the adapter pattern by creating an adapter object containing the adapted object and implementing the target interface. In a practical case, through the adapter mode, the client (such as MediaPlayer) can play advanced format media (such as VLC), although it itself only supports ordinary media formats (such as MP3).

PHP design pattern practical case analysis PHP design pattern practical case analysis May 08, 2024 am 08:09 AM

1. Factory pattern: Separate object creation and business logic, and create objects of specified types through factory classes. 2. Observer pattern: allows subject objects to notify observer objects of their state changes, achieving loose coupling and observer pattern.

PHP Design Patterns: Test Driven Development in Practice PHP Design Patterns: Test Driven Development in Practice Jun 03, 2024 pm 02:14 PM

TDD is used to write high-quality PHP code. The steps include: writing test cases, describing the expected functionality and making them fail. Write code so that only the test cases pass without excessive optimization or detailed design. After the test cases pass, optimize and refactor the code to improve readability, maintainability, and scalability.

How design patterns deal with code maintenance challenges How design patterns deal with code maintenance challenges May 09, 2024 pm 12:45 PM

Design patterns solve code maintenance challenges by providing reusable and extensible solutions: Observer Pattern: Allows objects to subscribe to events and receive notifications when they occur. Factory Pattern: Provides a centralized way to create objects without relying on concrete classes. Singleton pattern: ensures that a class has only one instance, which is used to create globally accessible objects.

What are the advantages and disadvantages of using design patterns in java framework? What are the advantages and disadvantages of using design patterns in java framework? Jun 01, 2024 pm 02:13 PM

The advantages of using design patterns in Java frameworks include: enhanced code readability, maintainability, and scalability. Disadvantages include complexity, performance overhead, and steep learning curve due to overuse. Practical case: Proxy mode is used to lazy load objects. Use design patterns wisely to take advantage of their advantages and minimize their disadvantages.

Application of design patterns in Guice framework Application of design patterns in Guice framework Jun 02, 2024 pm 10:49 PM

The Guice framework applies a number of design patterns, including: Singleton pattern: ensuring that a class has only one instance through the @Singleton annotation. Factory method pattern: Create a factory method through the @Provides annotation and obtain the object instance during dependency injection. Strategy mode: Encapsulate the algorithm into different strategy classes and specify the specific strategy through the @Named annotation.

See all articles