1 目的
将一个类的接口转换成客户希望的另外一个接口。adapter 模式使得原本由于接口不兼容
而不能一起工作的那些类可以一起工作。
有时,为复用而设计的工具箱类不能够被复用的原因仅仅是因为它的接口与专业应用领
域所需要的接口不匹配
2 使用场景
想使用以及存在的类, 但是他的接口不满足需求
想创建一个可以复用的类, 该类可以与其他不相关的类一起协同工作
3 使用方式
类适配器使用多重继承对一个接口与另一个接口进行匹配
对象匹配器依赖于对象组合
-
#include<iostream>
-
#include <deque>
-
using namespace std;
-
class Deque {
-
public:
-
void push_back(int x) { cout << "push back data " << x << "\n";}
-
void push_front(int x) { cout << "push front data " << x << "\n";}
-
void pop_back() { cout << "pop back\n"; }
-
void pop_front() { cout << "pop front\n"; }
-
};
-
-
class Sequence {
-
public:
-
virtual ~Sequence(){}
-
virtual void pop() = 0;
-
virtual void push(int x) = 0;
-
};
-
// 栈 后进后出
-
class Stack : public Sequence {
-
public:
-
void pop() { deque.pop_back(); }
-
void push(int x) { deque.push_back(x); }
-
private:
-
Deque deque;
-
};
-
//队列 后进前出
-
class Queue : public Sequence {
-
public:
-
void pop() { deque.pop_front(); }
-
void push(int x) { deque.push_back(x); }
-
private:
-
Deque deque;
-
};
-
-
int main(int argc, char* argv[]) {
-
Sequence *s1 = new Stack();
-
Sequence *s2 = new Queue();
-
s1->push(1); s1->pop();
-
s2->push(1); s2->pop();
-
delete s1; delete s2;
-
return 0;
-
}
编译文件
Makefile
-
# set CPUS for Linux or FreeBSD
-
CPUS := $(shell cat /proc/cpuinfo|grep -c processor)
-
-
-
GCC472_PATH=/usr/local/gcc-4.7.2
-
CXX := env LD_LIBRARY_PATH=$(GCC472_PATH)/lib:/usr/local/mpc/lib $(GCC472_PATH)/bin/g++
-
CXXFLAGS := -g3 -O2 -fno-strict-aliasing -Wall -Werror -fPIC \
-
-isystem /usr/local/include \
-
-isystem /usr/include
-
-
LDFLAGS := -pthread \
-
-L/usr/local/lib64/ \
-
-L/usr/local/lib/
-
RTFLAGS := \
-
-Wl,-rpath=.. \
-
-Wl,-rpath=/$(GCC472_PATH)/lib64
-
-
LIBS := -lpthread
-
-
SRC := $(wildcard *.cc)
-
OBJ := $(patsubst %.cc, %.o, $(SRC))
-
DEP := $(patsubst %.o, %.d, $(OBJ))
-
-
TARGET := main_test
-
-
all:
-
$(MAKE) -j$(CPUS) target
-
-
main_test: $(OBJ)
-
$(CXX) $^ -o $@ $(RTFLAGS) $(LDFLAGS) $(LIBS)
-
-
-
target: $(TARGET)
-
-
%.o : %.cc
-
$(CXX) -c $(CXXFLAGS) $< -o $@
-
-
%.d : %.cc
-
@$(CXX) -MM $< $(CXXFLAGS) | sed 's/$(notdir $*)\.o/$(subst /,\/,$*).o $(subst /,\/,$*).d/g' > $@
-
-
clean:
-
-rm -rf $(OBJ) $(TARGET) *.core $(DEP) *_unittest
-
-
test: all
-
./main_test
-
-
.PHONY: all target clean test
阅读(1447) | 评论(0) | 转发(0) |