码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式模式适配器

时间:2015-10-23 18:36:47      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

适配器模式定义:将一个类的接口,转换成客户期望的还有一个接口。适配器让原本接口不兼容的类能够合作无间。

简单定义:封装对象。并提供不同的接口

简单样例:

鸭子接口:

package headfirst.adapter.ducks;

public interface Duck {
	public void quack();
	public void fly();
}

详细鸭子:

package headfirst.adapter.ducks;

public class MallardDuck implements Duck {
	public void quack() {
		System.out.println("Quack");
	}
 
	public void fly() {
		System.out.println("I'm flying");
	}
}

火鸡接口:

package headfirst.adapter.ducks;

public interface Turkey {
	public void gobble();
	public void fly();
}

详细火鸡:

package headfirst.adapter.ducks;

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");
	}
}

将火鸡适配成鸭子:

package headfirst.adapter.ducks;

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();
		}
	}
}
測试:
package headfirst.adapter.ducks;

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 Turkey says...
Gobble gobble
I'm flying a short distance

The Duck says...
Quack
I'm flying

The TurkeyAdapter says...
Gobble gobble
I'm flying a short distance
I'm flying a short distance
I'm flying a short distance
I'm flying a short distance
I'm flying a short distance


版权声明:本文博主原创文章。博客,未经同意不得转载。

设计模式模式适配器

标签:

原文地址:http://www.cnblogs.com/hrhguanli/p/4905141.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!