适配器模式

适配器(Adapter)模式接受一种类型并提供一个对其他类型的接口。This is useful when you’re given a library or piece of code that has a particular interface, and you’ve got a second library or piece of code that uses the same basic ideas as the first piece, but expresses itself differently. If you adapt the forms of expression to each other, you can rapidly produce a solution.

现假设有个产生斐波那契数列的发生器类:

#ifndef FIBONACCIGENERATOR_H
#define FIBONACCIGENERATOR_H

class FibonacciGenerator {
	int n;
	int val[2];
public:
	FibonacciGenerator() : n(0) { val[0] = val[1] = 0; }
	int operator()() {
		int result = n > 2 ? val[0] + val[1] : n > 0 ? 1 : 0;	// 注意此处的用法
		++n;
		val[0] = val[1];
		val[1] = result;
		return result;
	}
	int count() { return n; }
};

#endif

由于它是一个发生器,可以调用operator()来使用它:

#include <iostream>
#include "FibonacciGenerator.h"
using namespace std;

int main() {
	FibonacciGenerator f;
	for(int i =0; i < 20; i++)
		cout << f.count() << ": " << f() << endl;
}

也午读者想用这相发生器来执行STL数值算法操作。遗憾的是,STL算法只能使用迭代器才能工作,这就存在接口不匹配的问题。解决方法是创建一个适配器,它将接受FibonacciGenerator并产生一个供STL算法使用的迭代器。由于数值算法只要求一个输入迭代器,该适配器模式相当地直观:

#include <iostream>
#include <numeric>
#include "FibonacciGenerator.h"
using namespace std;

class FibonacciAdapter{	// Produce an iterator
	FibonacciGenerator f;
	int length;

public:
	FibonacciAdapter(int size) : length(size) {}

	class iterator;
	friend class iterator;
	class iterator : public std::iterator<
		std::input_iterator_tag, FibonacciAdapter, ptrdiff_t>{
			FibonacciAdapter& ap;
			
	public:
		typedef int value_type;
		iterator(FibonacciAdapter& a) : ap(a){}
		bool operator==(const iterator&) const{
			return ap.f.count() == ap.length;
		}
		bool operator!=(const iterator& x) const{
			return !(*this == x);
		}
		int operator*() const{ return ap.f(); }
		iterator& operator++() { return *this; }
		iterator operator++(int) { return *this; }
	};
	iterator begin() { return iterator(*this); }
	iterator end() { return iterator(*this); }
};

int main() {
	const int SZ = 20;
	FibonacciAdapter a1(SZ);
	cout << "accumulate: "
		<< accumulate(a1.begin(), a1.end(), 0) << endl;
	FibonacciAdapter a2(SZ), a3(SZ);
	cout << "inner product: "
		<< inner_product(a2.begin(), a2.end(), a3.begin(), 0) << endl;
	FibonacciAdapter a4(SZ);
	int r1[SZ] = {0};
	int* end = partial_sum(a4.begin(), a4.end(), r1);
	//print(r1, end, "partial_sum", " ");
	FibonacciAdapter a5(SZ);
	int r2[SZ] = {0};
	end = adjacent_difference(a5.begin(), a5.end(), r2);
	//print(r2, end, "adjacent_difference", " ");
}

选自《C++编程思想》。

转载于:https://www.cnblogs.com/chinaxmly/archive/2012/09/30/2709429.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值