PHP设计模式---策略模式

最近,写策略模式的时候,发现和工厂模式差不多,有点混淆不清,特意说说的它们的差异。

  • 实现方式
    (1)工厂模式返回的就是一个对象工厂,让使用者自己调用相应的工厂方法,又叫创建行模式;
    (2)策略模式返回的是直接结果,无需触碰里面的实现方法(聚合),又叫行为模式。
  • 关注点
    (1)一个关注对象创建;
    (2)一个关注行为的封装。
<?php
	interface MathCal
	{
	    public function calcNumber($op1, $op2);
	}

	//Add-加法算法
	class MathAdd implements MathCal
	{
	    public function calcNumber($op1, $op2)
	    {
	        // TODO: Implement calcNumber() method.
	        return $op1 + $op2;
	    }
	}

	//Mult-乘法算法
	class MathMult implements MathCal
	{
	    public function calcNumber($op1, $op2)
	    {
	        // TODO: Implement calcNumber() method.
	        return $op2 * $op1;
	    }
	}
	
	class MathCalRealize
	{
	    protected $opc = null;
	
	    public function __construct($type)
	    {
	        $calc      = 'Math' . $type;
	        $this->opc = new $calc();
	    }
	    public function calc($op1,$op2) {
	        return $this->opc->calcNumber($op1,$op2);
	    }
	}

	$calc=new MathCalRealize('Add');
	$num=$calc->calc(4,10);
	echo $num.'<br>';
	
	$calc=new MathCalRealize('Mult');
	$num=$calc->calc(4,10);
	echo $num;
	
	# 上述可以看出,传入的参数,是独立的,各个算法端都是独立的;
	# 新增一个行为,只需要增加一个算法即可。
发布了46 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/tangqing24680/article/details/99969525