PHP设计模式之工厂模式详解

(编辑:jimmy 日期: 2024/10/3 浏览:2)

在开发大型系统时,往往会出现这样一种情况:

我有一部分基础数据,是类classA是从数据库A读取出来的,其他很多的功能都是基于这个基础数据来操作的。现在呢,我想把数据从数据库A变成从另外的数据源去获取,这时候,要修改起来就比较麻烦,要修改其他很多类的代码。这种设计显然是不够灵活的,换句话说,就是紧耦合的,那么什么是紧耦合呢?紧耦合就是指系统中某个部分的函数或类严重依赖于系统的其他部分中的函数或类的行为和结构。

这时,工厂模式的作用性就体现出来了。

工厂模式    

就是解决这样的一些情况的设计方法。

工厂模式是一种类,建立了一个工厂来根据所需来创建对象,这种方式在多态性编程中是很重要的,允许动态替换类,修改配置等。

/*基本工厂模式代码*/

<"htmlcode">
<"htmlcode">
<"htmlcode">
<?php

/** 
 * 抽象工厂模式 
 * */ 
 
interface userProperties { 
 function getUsername(); 
 function getGender(); 
 function getJob(); 
} 
 
interface createUser { //将对象的创建抽象成一个接口 
 function createOpen($properties);//内向创建 
 function createIntro($properties);//外向创建 
} 
 
class User implements userProperties{ 
 private $username; 
 private $gender; 
 private $job; 
 public function __construct($username, $gender, $job) { 
  $this->username = $username; 
  $this->gender = $gender; 
  $this->job = $job; 
 } 
 
 public function getUsername() { 
  return $this->username; 
 } 
 
 public function getGender() { 
  return $this->gender; 
 } 
 
 public function getJob() { 
  return $this->job; 
 } 
} 
 
class userFactory { 
 private $user; 
 public function __construct($properties = []) { 
  $this->user = new User($properties['username'], $properties['gender'], $properties['job']); 
 } 
 
 public function getUser() { 
  return $this->user; 
 } 
} 
 
class FactoryMan implements createUser { 
 function createOpen($properties) { 
  return new userFactory($properties); 
 } 
 
 function createIntro($properties) { 
  return new userFactory($properties); 
 } 
} 
 
class FactoryWoman implements createUser { 
 function createOpen($properties) { 
  return new userFactory($properties); 
 } 
 
 function createIntro($properties) { 
  return new userFactory($properties); 
 } 
} 
 
class clientUser { 
 static public function getClient($properties) { 
  $fac = new FactoryMan; 
  $man = $fac->createOpen($properties); 
  echo $man->getUser()->getUsername(); 
 } 
} 
 
$employers = [ 
 ['username' => 'Jack', 'gender' => 'male', 'job' => 'coder'], 
 ['username' => 'Marry', 'gender' => 'female', 'job' => 'designer'], 
 ]; 
$user = clientUser::getClient($employers[0]); 
?>

如有错误,请指正。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。