Adapter Pattern
下面是一个完整的适配器模式实例
public interface Duck
{
public void quack();
public void fly();
}
public class MallardDuck implements Duck
{
public void quack()
{
System.out.println(“Quack”);
}
public void fly()
{
System.out.println(“I’m flying”);
}
}
public interface Turkey
{
public void gobble();
public void fly();
}
public class WildTurkey implements Turkey
{
public void gobble()
{
System.out.println(“Gobble gobble”);
}
public void fly()
{
System.out.println(“I’m flying a short distance”);
}
}
// Adapter
public class TurkeyAdapter implements Duck
{
Turkey turkey;
public TurkeyAdapter(Turkey turkey)
{
this.turkey = turkey;
}
public void quack()
{
turkey.gobble();
}
public void fly()
{
for(int i=0; i < 5; i++) turkey.fly();
}
}
// test
public class DuckTestDrive
{
public static void main(String[] args)
{
MallardDuck duck = new MallardDuck();
WildTurkey turkey = new WildTurkey();
Duck turkeyAdapter = new TurkeyAdapter(turkey);
System.out.println(“The Turkey says...”);
turkey.gobble();
turkey.fly();
System.out.println(“\nThe Duck says...”);
testDuck(duck);
System.out.println(“\nThe TurkeyAdapter says...”);
testDuck(turkeyAdapter); }
static void testDuck(Duck duck)
{
duck.quack();
duck.fly();
}
}
对于上面适配器模式的一个解释
正式定义:
The Adapter Pattern converts the interface of a class into another interface the clients expect. Adapter lets classes work together that could not otherwise because of incompatible interfaces.
相应的一个图像表示:
事实上有两种适配器:object adapters 和 class adapters。上面的图就是一个 object adapter。而 class adapter 需要多重继承,这在 Java 中是不能实现的,但是并不意味着在其他场景不会遇到。
Object adapters and class adapters use two different means of adapting the adaptee (composition versus inheritance).
Facade Pattern
有时为了简化接口,将复杂的代码隐藏起来,我们需要使用Facade Pattern。下图给出了几种相近模式的不同意图:
正式定义:
The Facade Pattern provides a unified interface to a set of interface in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.
Least Knowledge 原则要求把对象之间的交互减少到只有最亲密的“朋友”才有。具体是这么说的:
Principle of Least Knowledge - talk only to your immedidate friends.
这意味着设计系统时,对于任何一个对象,都要控制和它交互的类的个数。但是应该怎么做呢?这一原则给出如下说明:
Now from any method in that object, the principle tells us that we should only invoke methods that belong to:
- The object itself
- Objects passed in as a parameter to the method
- Any object the method creates or instantiates
- Any components of the object
Notice that these guidelines tell us not call methods on objects that were returned from calling other method!!
一个例子: