search
HomeBackend DevelopmentPHP TutorialPHP simple factory pattern example PHP design pattern introductory tutorial

  1. /**

  2. * An example
  3. *
  4. * A farm wants to sell fruits to the market
  5. * There are three kinds of fruits on the farm, apples and grapes
  6. * We imagine: 1. Fruits have many attributes, and each attribute is different, but they have Common place | Growing, planting, receiving, eating
  7. * 2. New fruits may be added in the future. We need to define an interface to standardize the methods they must implement
  8. * 3. We need to obtain the class of a certain fruit, You need to get examples of a certain fruit from the farmer to know how to grow, plant, harvest and eat
  9. */
  10. /**

  11. * Virtual product interface class
  12. * Define the methods that need to be implemented
  13. */
  14. interface fruit{

  15. /**

  16. *Growth
  17. */
  18. public function grow();
  19. /**

  20. *Planting
  21. */
  22. public function plant();
  23. /**

  24. * Harvest
  25. */
  26. public function harvest();
  27. /**

  28. * Eat
  29. */
  30. public function eat();
  31. }
  32. /**

  33. * Define the specific product category Apple
  34. * First, we need to implement the methods defined by the inherited interface
  35. * Then define Apple-specific attributes and methods
  36. */
  37. class apple implements fruit{
  38. //苹果树有年龄

  39. private $treeAge;
  40. //苹果有颜色

  41. private $color;
  42. public function grow(){

  43. echo "grape grow";
  44. }
  45. public function plant(){

  46. echo "grape plant";
  47. }
  48. public function harvest(){

  49. echo "grape harvest";
  50. }
  51. public function eat(){

  52. echo "grape eat";
  53. }
  54. //取苹果树的年龄

  55. public function getTreeAge(){
  56. return $this->treeAge;
  57. }
  58. //设置苹果树的年龄

  59. public function setTreeAge($age){
  60. $this->treeAge = $age;
  61. return trie;
  62. }
  63. }

  64. /**

  65. * Define the specific product class Grape
  66. * First, we need to implement the methods defined by the inherited interface
  67. * Then define the unique attributes and methods of Grape
  68. */
  69. class grape implements fruit{
  70. //葡萄是否有籽

  71. private $seedLess;
  72. public function grow(){

  73. echo "apple grow";
  74. }
  75. public function plant(){

  76. echo "apple plant";
  77. }
  78. public function harvest(){

  79. echo "apple harvest";
  80. }
  81. public function eat(){

  82. echo "apple eat";
  83. }
  84. //有无籽取值

  85. public function getSeedLess(){
  86. return $this->seedLess;
  87. }
  88. //设置有籽无籽

  89. public function setSeedLess($seed){
  90. $this->seedLess = $seed;
  91. return true;
  92. }
  93. }
  94. /**

  95. *Farmer class is used to obtain instantiated fruits
  96. *
  97. */
  98. class farmer{
  99. //定义个静态工厂方法

  100. public static function factory($fruitName){
  101. switch ($fruitName) {
  102. case 'apple':
  103. return new apple();
  104. break;
  105. case 'grape':
  106. return new grape();
  107. break;
  108. default:
  109. throw new badFruitException("Error no the fruit", 1);
  110. break;
  111. }
  112. }
  113. }
  114. class badFruitException extends Exception{

  115. public $msg;
  116. public $errType;
  117. public function __construct($msg = '' , $errType = 1){
  118. $this->msg = $msg;
  119. $this->errType = $errType;
  120. }
  121. }
  122. /**

  123. * Method to obtain fruit instantiation
  124. */
  125. try{
  126. $appleInstance = farmer::factory('apple');
  127. var_dump($appleInstance);
  128. }catch(badFruitException $err){
  129. echo $err->msg . "_______" . $err->errType;
  130. }
复制代码


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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)