PHP-工厂方法模式

工厂方法规避了简单工厂的违反开放封闭原则;

结构:
有interface和abstract产品父类;
有实现父类的产品子类;

有interface和abstract工厂父类;
有实现父类的工厂子类;

示例:
Operation.php

<?php

namespace mulfactory;


abstract class Operation
{
	protected $numberA =0;
	protected $numberB =0;
	
	abstract public function getResult();
	
	public function setNumberA($number)
	{
		return $this->numberA=$number;
	}
	
		public function setNumberB($number)
	{
		return $this->numberB=$number;
	}
	
}

Add.php

<?php

namespace mulfactory;

class Add extends Operation
{
	public function getResult()
	{
		$result = $this->numberA+$this->numberB;
		return $result;
	}
}

Div.php

<?php

namespace mulfactory;

class Div extends Operation
{
	public function getResult()
	{
		if($this->numberB != 0){
			$result = $this->numberA/$this->numberB;
			return $result;
		}else{
			throw new \InvalidArgumentException('除数不能为零');
		}
	}
}

Mul.php

<?php
 
namespace mulfactory;

class Mul extends Operation
{
	public function getResult()
	{
		$result = $this->numberA*$this->numberB;
		return $result;
	}
}

Sub.php

<?php

namespace mulfactory;

class Sub extends Operation
{
	public function getResult()
	{
		$result = $this->numberA - $this->numberB;
		return $result;
	}
}

Factory.php

<?php

namespace mulfactory;

abstract class Factory
{
	abstract public function create();
}

AddFactory.php

<?php
namespace mulfactory;


class AddFactory extends Factory
{
	public function create()
	{
		return new Add();
	}
}

DivFactory.php

<?php
namespace mulfactory;

class DivFactory extends Factory
{
	public function create()
	{
		return new Div();
	}
	
}

MulFactory.php

<?php

namespace mulfactory;


class MulFactory extends Factory
{
	
	public function create()
	{
		return new Mul();
	}
}

SubFactory.php

<?php
namespace mulfactory;

class SubFactory extends Factory
{
	public function create()
	{
		return new Sub();
	}
}

index.php

<?php
require __DIR__.'/../Loader.php';

spl_autoload_register('Loader::autoload');//注册自动加载

$factory = new \mulfactory\AddFactory();
$operation = $factory->create();
$operation->setNumberA(1);
$operation->setNumberB(2);

$result = $operation->getResult();

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值