adapter模式的疑问!
问题1:Target 类存在的意义是什么?
GOF: “defines the domain-specific interface that Client uses.”个人觉得Target类的存在无关痛痒。但是我想不明白, 作者为什么要让它存在?
问题2:在GOF书中,多次强调Pluggable adapters。作者想表达什么意思?什么是可插入的adapters.意义何在?
原文如下:“A class is more reusable when you minimize the assumptions other classes must make to use it. By building interface adaptation into a class, you eliminate the assumption that other classes see the same interface. Put another way, interface adaptation lets us incorporate our class into existing systems that might expect different interfaces to the class. ObjectWorks\Smalltalk [Par90] uses the term pluggable adapter to describe classes with built-in interface adaptation.
Consider a TreeDisplay widget that can display tree structures graphically. If this were a special-purpose widget for use in just one application, then we might require the objects that it displays to have a specific interface; that is, all must descend from a Tree abstract class. But if we wanted to make TreeDisplay more reusable (say we wanted to make it part of a toolkit of useful widgets), then that requirement would be unreasonable. Applications will define their own classes for tree structures. They shouldn't be forced to use our Tree abstract class. Different tree structures will have different interfaces.
In a directory hierarchy, for example, children might be accessed with a GetSubdirectories operation, whereas in an inheritance hierarchy, the corresponding operation might be called GetSubclasses. A reusable TreeDisplay widget must be able to display both kinds of hierarchies even if they use different interfaces. In other words, the TreeDisplay should have interface adaptation built into it.”
[解决办法]
client 只需调用 Target的 方法 :
client::call( Target& t)
{
t.fun();
}
Target的子类 实现 真正的方法
class XXXTarget:public Target,proceted XXX
{
fun()
{
.... XXX::function() XXX 的方法,这样就把 XXX的方法适配成 Target.fun 了
}
}
XXXTarget xt;
client.call ( xt); //
[解决办法]
Target是一个抽象类,它只负责为客户提供一个接口。当客户调用的时候只关心 其内部的方法名字,其实现可以由提供者任意修改。
试想,如果没有这么一个类提供这些抽象的方法,用户第一次调用那些函数很正常,可是万一提供者要修改呢,把target类中的成员函数改了名字,那岂不是用户又要重新修改代码??
[解决办法]
[解决办法]
如果复用一些现存的类,但是接口又与客户端要求不一致的情况,那么Target 类的存在对客户端来说是提供了满足客户要求接口,并且如果被复用的类发生变动,那么这个变动的影响将被限制在Target 类里,Target 给客户端
提供的接口是稳定的。
[解决办法]
补充一下:Target是(标准)插座。
adapter(适配器)是标准插头,它一头连着插座(Target),一头连着非标准插头(adaptee被适配者)。
[解决办法]
学习.
[解决办法]
参见:
http://blog.csdn.net/alexjjf/articles/1353827.aspx