设计模式之工厂方法模式(php)

时间:2022-10-02 17:55:17

<?php

/**
* 工厂方法
*
*/

//抽象产品类
abstract class PenCore{
public $color;
abstract function writeWord($str);
}

//具体产品类
class RedPenCore extends PenCore {
function __construct(){
$this->color = "<font color='red'>红色</font>";
}

function writeWord($str){
echo "写出".$this->color."的字:$str";
}
}

class BluePenCore extends PenCore {
function __construct(){
$this->color = "<font color='blue'>蓝色</font>";
}

function writeWord($str){
echo "写出".$this->color."的字:$str";
}
}

class BlackPenCore extends PenCore {
function __construct(){
$this->color = "黑色";
}

function writeWord($str){
echo "写出".$this->color."的字:$str";
}
}


//抽象工厂类
abstract class BallPen{
function __construct(){
echo "生产了一支".$this->getPenCore()->color."笔芯的圆珠笔";
}

abstract function getPenCore();

}

//具体工厂类
class RedBallPen extends BallPen{
public function getPenCore(){
return new RedPenCore();
}
}

class BlueBallPen extends BallPen{
public function getPenCore(){
return new BluePenCore();
}
}

class BlackBallPen extends BallPen{
public function getPenCore(){
return new BlackPenCore();
}
}

echo "这个是工厂方法设计模式举例:<br/>";

$ballpen = new RedBallPen();
$penCore = $ballpen->getPenCore();
$penCore->writeWord("Hello world!");

echo "<br/>";
$ballpen = new BlueBallPen();
$penCore = $ballpen->getPenCore();
$penCore->writeWord("This is perfact!");


echo "<br/>";
$ballpen = new BlackBallPen();
$penCore = $ballpen->getPenCore();
$penCore->writeWord("It's OK!");

工厂方法:用户不必知道他所使用的对象如何创建的,只是需要知道用哪些方法可以使用即可。