【发布时间】:2012-07-03 06:52:15
【问题描述】:
阅读 Elecias White 的书“制作嵌入式系统”(来自 O'Reilly)让我感到困惑,因为这两个术语:外观和适配器模式。她对两者的解释根本不清楚。
Adapter Pattern (Pag, 19): "(...有时称为包装器) 它将对象的接口转换为对客户来说更容易的接口。...通常,适配器是在软件 API 之上编写的,以隐藏丑陋的接口……”.
外观模式(第 86 页):“...它为一段代码提供了简化的界面...”。 然后它说 “...适配器模式是外观模式的更通用版本”。
遗憾的是,这两个术语对我来说似乎很相似。
根据本网站(和其他)中的其他定义,大多数人说“适配器模式使两个不兼容的接口兼容”。在这种情况下,“不兼容”这个词是什么意思?
大多数网站和书籍都从嵌入式系统的角度(纯 C,而不是 OOP)以外的更高级别给出了关于模式的定义,因此给出的示例确实不清楚。
值得一提的是,虽然这本书是一本极好的知识来源,但对于新手和专业人士来说,它并没有包含这么多代码,所以人们应该弄清楚这种定义。
我试图通过我为自己写的几个例子来理解它们,你能指出我的理解是否正确吗?
示例 1,外观模式:
/* This is a fancy API that I want to 'facade' */
fancy_gui_DrawWidget(parent, id, x0, y0, x1, y1, text, txt_color, back_color, brdr_color, draw_callback(), ... and more parameters)
{
/* draw the widget */
}
/* Here I'm using the 'facade pattern' */
mygui_DrawButton(parent, id, x, y, width, height, text)
{
...
x1=x+width;
y1=y+height;
...
fancy_gui_DrawWidget(parent, id, x, y, x1, y1, text, BLACK, WHITE, ORANGE, button_draw_fn, ... and some more parameters needed);
}
示例 2,适配器模式:
/* Ugly interface that I want to 'adapt' (from LPC17xx NXP's CMSIS library) */
uint32_t UART_Send(
LPC_UART_TypeDef *UARTx,
uint8_t *txbuf,
uint32_t buflen,
TRANSFER_BLOCK_Type flag)
{
/* transmits the txbuf */
}
/* Here I'm using the 'adapter pattern' (I think so) for a good looking interface */
int uart0_Send(buffer, len_buffer)
{
/* Do some stuff */
len=UART_Send(uart0_handler,buffer,len_buffer, BLOCKING);
if(len!=len_buffer)
return 0;
return 1;
}
希望我自己解释得足够好。提前谢谢你!
【问题讨论】:
-
加入代理模式,让自己更加困惑:)
标签: design-patterns embedded adapter facade