适配器模式

适配器(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

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    适配器模式

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/64308

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 上午11:23
下一篇 2023年2月9日 上午11:23

相关推荐