欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Adapter patten 读书笔记

程序员文章站 2024-03-01 08:53:16
...
将一个类的接口,转换成客户期待的另一个接口。适配器让原本接口不兼容的类可以合作无间。
[img]http://blufiles.storage.live.com/y1pZ1u4rC44uChXwIBFqK5mLwHk6r-HEfZ67jPky-gBcOUn31HWvxQplIuoXiZpseq19BNc5lqxwP0[/img]
package pattern;
interface Turkey {
public void gobble();
public void fly();
}
class WildTurkey implements Turkey{
public WildTurkey(){}
public void gobble(){
System.out.println("Gobble gobble");
}
public void fly(){
System.out.println("i am flying a short distance");
}
}
interface DuckInterface{
public void quack();
public void fly();
}
class MallardDuckinterface implements DuckInterface{
public MallardDuckinterface(){}
public void quack(){
System.out.println("quack");
}
public void fly(){
System.out.println("i am fly");
}
}
class TurkeyAdapter implements DuckInterface{
Turkey turkey;
public TurkeyAdapter(Turkey turkey){
turkey=turkey;
}
public void quack(){
turkey.gobble();
}
public void fly(){
for(int i=0;i<5;i++){
turkey.fly();
}
}
}
class DuckAdapter implements Turkey{
DuckInterface duckInterface;
public void DuckAdapter(DuckInterface duckInterface){
duckInterface=duckInterface;
}
public void gobble(){
duckInterface.quack();
}
public void fly(){
duckInterface.fly();
}
}
package pattern;
public class DuckTestDrive {
public static void main(String[] args) {
DuckInterface duck=new MallardDuckinterface();
WildTurkey turkey= new WildTurkey();

DuckInterface turkeyAdapter=new TurkeyAdapter(turkey);
System.out.println("The Turkey says...");
turkey.gobble();
turkey.fly();

System.out.println("\n The Duck says...");
testDuck(duck);

System.out.println("\n The TurkeyAdapter says...");
//testDuck(turkeyAdapter);
turkeyAdapter.quack();
}
static void testDuck(DuckInterface duck){
duck.quack();
duck.fly();
}
}
相关标签: 读书