PHP design mode: Factory mode

Source: Internet
Author: User
Tags php class
Factory mode:

By the factory class according to the parameters to decide which product class to create an instance;

A factory class is a class that contains a method that is designed to create other objects. The so-called on demand, incoming parameters to select, return the specific class. The most important role of the factory pattern is the encapsulation of object creation, simplifying the creation of object operations.

Simply put, call a method of the factory class (incoming parameters) to get the required class;

Code implementation:

Example 1 (the most basic factory Class):

<?php class MyObject {public Function __construct () {} public Function test () {return ' Test ',}} class MyFactory {public static function Factory () {//Returns an instance of the object return new MyObject ();}} Call the static method in the factory class MyFactory to get an instance of Class MyObject $myobject=myfactory::factory (); Echo $myobject->test ();

Example 2:

<?php//Simple Factory Mode/1* * Define operation class */abstract class Operation {protected $_numbera = 0;protected $_numberb = 0;protected $_resul t = 0; Public function __construct ($A, $B) {$this->_numbera = $A; $this->_numberb = $B;} public Function Setnumber ($A, $B) {$ This->_numbera = $A; $this->_numberb = $B;} /1*protected function Clearresult () {$this->_result = 0;} */Public Function Clearresult () {$this->_result = 0;}//abstract method without method body abstract protected function getresult (); }//Inherit an abstract class, the subclass must implement all abstract methods in the abstract class;//In addition, the visibility of these methods must be the same as in the abstract class (or more relaxed) class Operationadd extends operation {public function GetResult () {$this->_result= $this->_numbera + $this->_numberb;return $this->_result;}} Class Operationsub extends Operation {public Function GetResult () {$this->_result= $this->_numbera-$this->_ Numberb;return $this->_result;} } class Operationmul extends operation {public Function GetResult () {$this->_result= $this->_numbera * $this->_ Numberb;return $this->_result;} } class OPerationdiv extends Operation {public Function GetResult () {$this->_result= $this->_numbera/$this->_numberb; return $this->_result;} } class Operationfactory {//Create a static member variable that holds the instance private static $obj;//Create a public static method that accesses the instance. Type, $A, $B) {switch ($type) {case ' + ': self:: $obj = new Operationadd ($A, $B); Break;case '-': self:: $obj = new Operationsub ($ A, $B); Break;case ' * ': self:: $obj = new Operationmul ($A, $B); Break;case '/': self:: $obj = new Operationdiv ($A, $B); Return self:: $obj;} }//$obj = operationfactory::createoperation (' + ');//$obj->setnumber; $obj = operationfactory:: CreateOperation (' * ', 5,6); Echo $obj->getresult ();/1*echo ' <br> '; $obj->clearresult (); Echo ' <br> '; Echo $obj->_result;*/

Example 3:

<?php//Abstract Factory//Bronze member's discounted item class Bronzerebatecommodity {//description public $desc = ' Bronze member's discounted item ';}//Silver member's discounted product class silverrebatecommodity {public $desc = ' Silver Member's discounted item ';}//Bronze member's recommended product class Bronzecommendatorycommodity {public $desc = ' Bronze member's recommended product ';} Silver member's recommended product class Silvercommendatorycommodity {public $desc = ' Silver Member's recommended product ';}//interface of each factory interface Concretefactory {// Method of the Production object public function create ($what);} Bronze Factory class Bronzefactory implements Concretefactory {//method of Production object public function Create ($what) {$productName = ' Bronze '. $ What. ' commodity '; return new $productName;} }//Silver factory class Silverfactory implements Concretefactory {//method of Production object public function Create ($what) {$productName = ' silver '. $what. ' Commodity '; return new $productName;} }//Dispatch center class Centerfactory {//Get Factory method Public function GetFactory ($what) {$factoryName = $what. ' Factory '; return new $ Factoryname;} Gets the static method of the factory public static function GetFactory2 ($what) {$factoryName = $what. ' Factory '; return new $factoryName;}} Instantiate dispatch Center $center = new Centerfactory ();//Get a silverFactory $factory = $center->getfactory (' silver ');//Let the Silver Factory make a recommended product $product = $factory->create (' commendatory ');// Get the silver member's recommended product echo $product->desc. ' <br> '; Get a bronze factory $factory2 = Centerfactory::getfactory2 (' Bronze ');//Let the Bronze factory produce a discounted item $product2 = $factory 2->create ('

Example 4:

&LT;?PHP//uses the factory class to parse the image file interface IImage {function getwidth (); function getheight (); function getData ();} class Image_png Implements IImage {protected $_width,$_height,$_data; public function __construct ($file) {$this->_file = $file; $ This->_parse ();} Private Function _parse () {//Finish parsing work in PNG format//and populate $_width,$_height and $_data$this->_data = getimagesize ($this->_file List ($this->_width, $this->_height) = $this->_data;} Public Function getwidth () {return $this->_width,} public Function getheight () {return $this->_height; function GetData () {return $this->_data;}} Class Image_jpeg implements IImage {protected $_width,$_height,$_data; public function __construct ($file) {$this->_ File = $file; $this->_parse ();} Private Function _parse () {//Finish parsing work in JPEG format//and populate $_width,$_height and $_data//$this->_width = imagesx ($this->_file) ;//$this->_height = Imagesy ($this->_file); $this->_data = getimagesize ($this->_file); list ($this->_ width, $this->_height) = $tHis->_data;} Public Function getwidth () {return $this->_width,} public Function getheight () {return $this->_height; function GetData () {return $this->_data;}} Factory class Imagefactory {public static function factory ($file) {$filename = PathInfo ($file); switch (Strtolower ($ filename[' extension ')) {case ' jpg ': $return = new Image_jpeg ($file); Break;case ' png ': $return = new Image_png ($file); Break;default:echo ' picture type is incorrect '; if ($return instanceof IImage) {return $return;} Else{echo ' error '; exit ();}} } $image = Imagefactory::factory (' images/11.jpg '); Var_dump ($image->getwidth ()); Echo ' <br> ';p rint_r ($ Image->getheight ()); Echo ' <br> ';p rint_r ($image->getdata ());



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.