9、策略模式

思考: 如果想增加取模运算又如何操作?

想一想简单工厂方法,是否有些相似? 又有哪些不同?

通过接口,隔离封装

通过继承,适应变化


工厂模式,我们着眼于得到对象,并操作对象,
策略模式,我们着重得到对象某方法的运行结果

<form method="post" action="">
	<input type="text" name="op1">
	<select name="op">
		<option value="Add">+</option>
		<option value="Sub">-</option>
		<option value="Mul">*</option>
		<option value="Div">/</option>
	</select>
	<input type="text" name="op2">
	<input type="submit" value="计算">
</form>
<?php

interface Math
{
	public function calc($op1, $op2);
}

class MathAdd implements Math
{
	public function calc($op1, $op2)
	{
		return $op1 + $op2;
	}
}

class MathSub implements Math
{
	public function calc($op1, $op2)
	{
		return $op1 - $op2;
	}
}

class MathMul implements Math
{
	public function calc($op1, $op2)
	{
		return $op1 * $op2;
	}
}

class MathDiv implements Math
{
	public function calc($op1, $op2)
	{
		return $op1 / $op2;
	}
}

//传来op,制造不同对象,并且调用

//封装一个虚拟计算器
class CMath
{
	protected $calc = null;

	public function __construct($type)
	{
		$calc = 'Math' . $type;
		$this->calc = new $calc();
	}

	public function calc($op1, $op2)
	{
		return $this->calc->calc($op1, $op2);
	}
}

$type = isset($_POST['op']) ? $_POST['op'] : '';
$op1 = isset($_POST['op1']) ? $_POST['op1'] : '';
$op2 = isset($_POST['op2']) ? $_POST['op2'] : '';
$cmath = new CMath($type);
echo $cmath->calc($op1, $op2);


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++中的策略模式是一种行为型设计模式,它允许在运行时选择算法的不同实现。该模式定义了一组算法,将它们各自封装起来,并使它们可以互换。 在C++中,可以使用函数指针、函数对象或Lambda表达式来实现策略模式。以下是一个简单的示例: ```c++ #include <iostream> class SortingStrategy { public: virtual void sort(int* arr, int n) = 0; }; class BubbleSort : public SortingStrategy { public: void sort(int* arr, int n) { // Bubble sort implementation std::cout << "Sorting using bubble sort." << std::endl; } }; class QuickSort : public SortingStrategy { public: void sort(int* arr, int n) { // Quick sort implementation std::cout << "Sorting using quick sort." << std::endl; } }; class Sorter { private: SortingStrategy* strategy; public: void setSortingStrategy(SortingStrategy* newStrategy) { strategy = newStrategy; } void sort(int* arr, int n) { strategy->sort(arr, n); } }; int main() { int arr[] = {5, 2, 9, 3, 6}; int n = sizeof(arr) / sizeof(arr[0]); Sorter sorter; BubbleSort bubbleSort; sorter.setSortingStrategy(&bubbleSort); sorter.sort(arr, n); QuickSort quickSort; sorter.setSortingStrategy(&quickSort); sorter.sort(arr, n); return 0; } ``` 在上面的示例中,SortingStrategy是抽象策略类,BubbleSort和QuickSort是具体策略类。Sorter是使用策略模式的上下文类,它可以使用setSortingStrategy方法设置当前使用的SortingStrategy实现,并在sort方法中使用该实现对输入数组进行排序。 运行上面的代码将输出: ``` Sorting using bubble sort. Sorting using quick sort. ``` 这表明程序成功地使用了策略模式来选择不同的排序算法实现。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值