search
HomeBackend DevelopmentPHP Tutorial实例讲解PHP设计模式编程中的简单工厂模式_php实例

简单工厂模式是类的创建模式,又叫做静态工厂方法(Static Factory Method)模式。简单工厂模式是由一个工厂对象决定创建出那一种产品类的实例。

1.工厂模式的几种形态
工厂模式专门负责将大量有共同接口的类实例化。工厂模式可以动态决定将哪一个类实例化,不必事先知道每次要实例化哪一个类。工厂模式有以下几种形态:
(1)简单工厂(Simple Factory)模式,又称静态工厂方法模式(Static Factory Method Pattern)。
(2)工厂方法(Factory Method)模式,又称多态性工厂(Polymorphic Factory)模式或虚拟构造子(Virtual Constructor)模式;
(3)抽象工厂(Abstract Factory)模式,又称工具箱(Kit 或Toolkit)模式。下面就是简单工厂模式的简略类图。

简单工厂模式,或称静态工厂方法模式,是不同的工厂方法模式的一个特殊实现。在其他文献中,简单工厂往往作为普通工厂模式的一个特例讨论。
学习简单工厂模式是对学习工厂方法模式的一个很好的准备,也是对学习其他模式,特别是单例模式和多例模式的一个很好的准备。

2 .简单工厂模式的引进

比如说有一个农场公司,专门向市场销售各类水果。在这个系统里需要描述下列的水果:
葡萄 Grape
草莓 Strawberry
苹果 Apple
水果与其他的植物有很大的不同,就是水果最终是可以采摘食用的。那么一个自然的作法就是建立一个各种水果都适用的接口,以便与农场里的其他植物区分开。如下图所示。

水果接口规定出所有的水果必须实现的接口,包括任何水果类必须具备的方法:种植plant(),生长grow()以及收获harvest()。接口Fruit 的类图如下所示。

这个水果接口的源代码如下所示。
代码清单1:接口Fruit 的源代码

interface Fruit
{
public function grow();
public function harvest();
public function plant();
}

Apple 类是水果类的一种,因此它实现了水果接口所声明的所有方法。另外,由于苹果是多年生植物,因此多出一个treeAge 性质,描述苹果树的树龄。下面是这个苹果类的源代码。
代码清单2:类Apple 的源代码

class Apple implements Fruit
{
private $_treeAge;
public function grow()
{
echo "Apple is growing.";
}
public function harvest()
{
echo "Apple has been harvested.";
}
public function plant()
{
echo "Apple has been planted.";
}
public function getTreeAge()
{
return $this->_treeAge;
}
public function setTreeAge($treeAge)
{
$this->_treeAge = (int) $treeAge;
}
}

同样,Grape 类是水果类的一种,也实现了Fruit 接口所声明的所有的方法。但由于葡萄分有籽和无籽两种,因此,比通常的水果多出一个seedless 性质,如下图所示。

葡萄类的源代码如下所示。可以看出,Grape 类同样实现了水果接口,从而是水果类型的一种子类型。
代码清单3:类Grape 的源代码

class Grape implements Fruit
{
private $seedless;
public function grow()
{
echo "Grape is growing.";
}
public function harvest()
{
echo "Grape has been harvested.";
}
public function plant()
{
echo "Grape has been planted.";
}
public function getSeedless()
{
return $this->seedless;
}
public function setSeedless($seedless)
{
$this->seedless = (boolean) $seedless;
}
}

Strawberry 类实现了Fruit 接口,因此,也是水果类型的子类型,其源代码如下所示。
代码清单4:类Strawberry 的源代码

class Strawberry implements Fruit
{
public function grow()
{
echo "Strawberry is growing.";
}
public function harvest()
{
echo "Strawberry has been harvested.";
}
public function plant()
{
echo "Strawberry has been planted.";
}
}

农场的园丁也是系统的一部分,自然要由一个合适的类来代表。这个类就是FruitGardener 类,其结构由下面的类图描述。

FruitGardener 类会根据客户端的要求,创建出不同的水果对象,比如苹果(Apple),葡萄(Grape)或草莓(Strawberry)的实例。而如果接到不合法的要求,FruitGardener 类会抛出BadFruitException 异常。
园丁类的源代码如下所示。
代码清单5:FruitGardener 类的源代码

class FruitGardener
{
public static function factory($which)
{
$which = strtolower($which);
if ($which == 'apple') {
return new Apple();
} elseif ($which == 'strawberry') {
return new Strawberry();
} elseif ($which == 'grape') {
return new Grape();
} else {
throw new BadFruitException('Bad fruit request');
}
}
}

可以看出,园丁类提供了一个静态工厂方法。在客户端的调用下,这个方法创建客户端所需要的水果对象。如果客户端的请求是系统所不支持的,工厂方法就会抛出一个BadFruitException 异常。这个异常类的源代码如下所示。
代码清单6:BadFruitException 类的源代码

class BadFruitException extends Exception
{
}

在使用时,客户端只需调用FruitGardener 的静态方法factory()即可。请见下面的示意
性客户端源代码。
代码清单7:怎样使用异常类BadFruitException

try {
FruitGardener::factory('apple');
FruitGardener::factory('grape');
FruitGardener::factory('strawberry');
//...
} catch (BadFruitException $e) {
//...
}

这样,农场一定会百果丰收啦!

3.使用简单工厂模式设计一个“面向对象的”计算器

/**
 * 面向对象计算器
 * 思路:
 * 1、面向对象的基本,封装、继承、多太
 * 2、父类公用类
 * 3、各种运算类
 */
 
/**
 * 基类,运算类
 * 只提供基本数据,不参与运算
 */
 
class Operation {
  
 // 第一个数
 public $first_num = 0;
  
 // 第二个数
 public $second_num = 0;
  
 /**
  * 获取结果,其他类覆盖此方法
  * @return double $result
  */
 public function getResult() {
  $result = 0.00;
   
  return $result;
 }
}
 
/**
 * 加法类
 */
class OperationAdd extends Operation {
 /**
  * 覆盖父类,实现加法算法
  */
 public function getResult() {
  $result = 0;
  return $this->first_num + $this->second_num;
 }
}
 
/**
 * 减法类
 *
 */
class OperationSub extends Operation {
 /**
  * 覆盖父类,实现加法算法
  */
 public function getResult() {
  $result = 0;
  return $this->first_num - $this->second_num;
 }
}
 
/**
 * 乘法类
 *
 */
class OperationMul extends Operation {
 /**
  * 覆盖父类,实现加法算法
  */
 public function getResult() {
  $result = 0;
  return $this->first_num * $this->second_num;
 }
}
 
/**
 * 除类
 *
 */
class OperationDiv extends Operation {
 /**
  * 覆盖父类,实现加法算法
  */
 public function getResult() {
  $result = 0;
   
  if ($this->second_num == 0) {
   throw new Exception('除法操作第二个参数不能为零!');
   return 0;
  }
   
  return $this->first_num / $this->second_num;
 }
}
 
/**
 * 工厂类
 */
class OperationFactory {
 /**
  * 工厂函数
  * @param string $operation
  * @return object
  */
 public function createOperation($operation) {
  $oper = null;
   
  switch($operation) {
   case '+':
    $oper = new OperationAdd();
    break;
   case '-':
    $oper = new OperationSub();
    break;
   case '*':
    $oper = new OperationMul();
    break;
   case '/':
    $oper = new OperationDiv();
    break;
   default:
    return 0;
  }
  return $oper;
 }
}
 
 
$operation = new OperationFactory();
$oper = $operation->createOperation('/');
 
$oper->first_num = 10;
$oper->second_num = 20;
var_dump($oper->getResult());

201622993823532.jpg (780×328)

Statement
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
PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP: The Foundation of Many WebsitesPHP: The Foundation of Many WebsitesApr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

See all articles

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools