天天看點

head first-----------adpter pattern

head first-----------------深入淺出擴充卡模式

     擴充卡模式:将一個類的接口,轉換成客戶想要的另外一個接口,擴充卡然原本接口不相容的類可以合作無間。進而可以不用更改舊的代碼就可以适應新的業務需求

     package com.clark.adapterpattern.abstractclass;

/**

 * Duck 接口

 * @author Administrator

 *

 */

public interface Duck {

public void quack();//呱呱叫方法

public void fly();//鴨子會飛

}

package com.clark.adapterpattern.abstractclass;

 * 火雞接口

public interface Turkey {

public void gobble();//火雞嘎嘎叫

public void fly();//火雞也會飛,隻是飛得短

package com.clark.adapterpattern;

import com.clark.adapterpattern.abstractclass.Duck;

 * 綠頭鴨

public class MallardDuck implements Duck {

@Override

public void quack() {

System.out.println("Quack.......");

public void fly() {

System.out.println("fly remote distance.......");

import com.clark.adapterpattern.abstractclass.Turkey;

 * 火雞的具體實作

public class WildTurkey implements Turkey {

public void gobble() {

System.out.println("Gobble gobble.....");

System.out.println("fly short distance.....");

import java.util.Random;

 * 鴨子轉換成火雞的擴充卡

public class DuckAdpter implements Turkey {

public Duck duck;

public Random rand;

public DuckAdpter(Duck duck){

this.duck=duck;

rand=new Random();

this.duck.quack();

if(rand.nextInt(5)==0){

this.duck.fly();

 * 火雞轉化成鴨子的擴充卡

public class TurkeyAdpter implements Duck {

public Turkey turkey;

public TurkeyAdpter(Turkey turkey){

this.turkey=turkey;

this.turkey.gobble();

//由于火雞飛得距離短,是以讓它多飛幾次

for (int i = 0; i < 3; i++) {

this.turkey.fly();

 * Test CLASS

public class TestDrive {

public static void main(String[] args) {

//先建立一隻鴨子和一隻火雞

MallardDuck duck=new MallardDuck();

WildTurkey turkey=new WildTurkey();

//然後将火雞包裝進火雞擴充卡,鴨子裝到鴨子擴充卡

Duck turkryAdpter=new TurkeyAdpter(turkey);

Turkey DuckAdpter=new DuckAdpter(duck);

//列印原來火雞和鴨子的行為

System.out.println("The Turkey says.....");

turkey.gobble();

turkey.fly();

System.out.println("\nThe Duck says.....");

testDuck(duck);

//使用擴充卡之後輸出的行為

System.out.println("\nThe turkeyadpter says....");

testDuck(turkryAdpter);

System.out.println("\nThe turkeyAdpter says....");

testTurkey(turkey);

public static void testDuck(Duck duck){

duck.quack();

duck.fly();

public static void testTurkey(Turkey turkey){

//=============Test result================

The Turkey says.....

Gobble gobble.....

fly short distance.....

The Duck says.....

Quack.......

fly remote distance.......

The turkeyadpter says....

The turkeyAdpter says....

ide