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

<?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!");

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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值