PHP design mode-Simple Factory mode (static Factory method mode), PHP design mode _php Tutorial

Source: Internet
Author: User

PHP design mode-Simple Factory mode (static Factory method mode), PHP design mode


Concept

Simple Factory mode "static Factory method Mode" (Static Factory methods)
is the creation mode of the class

Several forms of Factory mode:
1. Simple Factory | Also known as the Static Factory method pattern (static Factory methods)
2. Factory method Mode (Factory) | Also known as polymorphism Factory mode (polymorphic Factory)
3, abstract Factory mode (abstract Factory) | Also known as Toolbox mode (TOOLKIT)

Image matching

Code instance

Run the code directly, it's all tested

1 
 Php2 3 /**4 * one case5  *6 * A farm that sells fruit to the market7 * There are three kinds of fruit apples and grapes on the farm.8 * We envision: 1, fruit has a variety of properties, each attribute is different, but they have a common place | Growing, planting, receiving, eating9 * 2, in the future it is possible to add new fruits, we need to define an interface to standardize the methods they must implementTen * 3, we need to get a class of fruit, to get a sample of a fruit from the farmer to know how to grow, grow, receive, eat One  */ A  -  - /** the * Virtual Product interface Class - * Define the methods that need to be implemented -  */ -  + Interfacefruit{ -  +     /** A * Growth at      */ -      Public functiongrow (); -  -     /** - * Planting -      */ in      Public functionplant (); -  to     /** + * Harvest -      */ the      Public functionHarvest (); *  $     /**Panax Notoginseng * Eat -      */ the      Public functioneat (); +      A } the  +  - /** $ * Define specific product classes Apple $ * First, we want to implement the method defined by the inherited interface - * Then define the properties that are unique to Apple, and how -  */ the classAppleImplementsfruit{ - Wuyi     //The Apple tree has an age the     Private $treeAge; -  Wu     //Apples have color -     Private $color; About  $      Public functiongrow () { -         Echo"Grape Grow"; -     } -  A      Public functionplant () { +         Echo"Grape Plant"; the     } -  $      Public functionHarvest () { the         Echo"Grape Harvest"; the     } the  the      Public functioneat () { -         Echo"Grape eat"; in     } the  the     //take the age of the apple tree About      Public functionGettreeage () { the         return $this-TreeAge; the     } the  +     //set the age of the apple tree -      Public functionSettreeage ($age){ the         $this->treeage =$age;Bayi         returntrie; the     } the  - } -  the /** the * Definition of specific product category grape the * First, we want to implement the method defined by the inherited interface the * Then define the properties specific to the grape, and the method -  */ the classGrapeImplementsfruit{ the  the 94     //whether the grapes have seeds the     Private $seedLess; the  the      Public functiongrow () {98         Echo"Apple Grow"; About     } - 101      Public functionplant () {102         Echo"Apple Plant";103     }104  the      Public functionHarvest () {106         Echo"Apple Harvest";107     }108 109      Public functioneat () { the         Echo"Apple eat";111     } the 113     //there is no seed to take value the      Public functiongetseedless () { the         return $this-seedless; the     }117 118     //set with seeds and no seeds119      Public functionSetseedless ($seed){ -         $this->seedless =$seed;121         return true;122     }123 124 } the 126 127 /** - * farmers ' classes are used to obtain instanced fruit129  * the  */131 classfarmer{ the 133     //define a static factory method134      Public Static functionFactory$fruitName){135         Switch($fruitName) {136              Case' Apple ':137                 return NewApple ();138                  Break;139              Case' Grape ': $                 return Newgrape ();141                  Break;142             default:143                 Throw NewBadfruitexception ("Error No The Fruit", 1);144                  Break;145         }146     }147 }148 149 classBadfruitexceptionextends Exception{ Max      Public $msg;151      Public $errType; the      Public function__construct ($msg= '' ,$errType= 1){153         $this->msg =$msg;154         $this->errtype =$errType;155     }    156 }157 158 159 /** the * ways to get fruit instantiation161  */162 Try{163     $appleInstance= Farmer::factory (' Apple ');164     Var_dump($appleInstance);165}Catch(badfruitexception$err){166     Echo $err->msg. "_______" .$err-Errtype;167}


PHP design Pattern: Write the PHP5 sample code for factory and single mode

Example #1 Call factory method (with parameters)

Class Example
{
The Parameterized factory method
public static function factory ($type)
{
if (include_once ' drivers/'. $type. '. php ') {
$classname = ' Driver_ '. $type;
return new $classname;
} else {
throw new Exception (' Driver not found ');
}
}
}
?>
------------------------------------
Example #2 Single case mode

Class Example
{
Save the class instance in this property
private static $instance;

The construction method is declared private, preventing the object from being created directly
Private Function __construct ()
{
Echo ' I am constructed ';
}

Singleton method
public static function Singleton ()
{
if (!isset (self:: $instance)) {
$c = __class__;
Self:: $instance = new $c;
}

Return self:: $instance;
}

Common methods in the example class
Public Function bark ()
{
Echo ' woof! ';
}

Prevent users from replicating object instances
Public Function __clone ()
{
Trigger_error (' Clone is not allowed. ', e_user_error);
}

}

?>

The similarities and differences between the simple factory model and the factory method mode?

The LZ to recommend a simple factory, factory methods and abstract factory together under the study, hehe, the previous part of my teacher let me study the different of these 3 models, learning together may be more clear. The
Simple Factory mode is also called the Static factory method mode. Renaming can tell that this pattern must be simple. The purpose of its existence is simple: Define an interface for creating objects.
Take a look at its composition:
1) Factory class role: This is the core of this model, contains certain business logic and judgment logic. In Java it is often implemented by a specific class.
2) Abstract product role: It is generally the parent class or interface of the specific product inheritance. Implemented in Java by an interface or an abstract class.
3) Specific product roles: the object created by the factory class is an instance of this role. Implemented in Java by a concrete class. The
Factory method pattern removes the static property of the factory method in the simple Factory mode so that it can inherit from the quilt class. The pressure to concentrate on factory methods in a simple factory model can be shared by different factory subclasses in the factory method model.
Look at its composition:
1) Abstract Factory role: This is the core of the factory method pattern, and it is not application-agnostic. is the interface that the specific factory role must implement or the parent class that must inherit. In Java it is implemented by an abstract class or interface.
2) Specific factory role: It contains code that is relevant to the specific business logic. Called by the application to create an object that corresponds to a specific product.
3) Abstract product role: It is the parent of a specific product inheritance or an implemented interface. In Java, there are generally abstract classes or interfaces to implement.
4) Specific product roles: the object created by the specific factory role is an instance of this role. Implemented in Java by a specific class.
 

http://www.bkjia.com/PHPjc/873921.html www.bkjia.com true http://www.bkjia.com/PHPjc/873921.html techarticle PHP design mode-Simple Factory mode (static Factory method mode), PHP design pattern concept Simple Factory mode "static Factory method Mode" (Static Factory methods) is the creation mode of the class ...

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.