企業(yè)網(wǎng)站制作簡(jiǎn)介bt螞蟻
類模式
我們知道插座的電壓為交流電220V,而日常電器使用的是直流電且電壓會(huì)較小,比如手機(jī)充電會(huì)通過(guò)插頭適配器達(dá)到額定的輸入電流。下面我們實(shí)現(xiàn)這個(gè)案例:將220V電壓轉(zhuǎn)化為5V的電壓。
?
package Adapter.Class;public class Adapter extends Power220V implements Power5V {@Overridepublic int output5V() {int input = output220V();int output = input/44;return output;}
}
package Adapter.Class;public class Client {public static void main(String[] args) {Phone phone = new HuaWei();phone.charging(new Adapter());}
}
package Adapter.Class;public class HuaWei implements Phone{@Overridepublic void charging(Adapter adapter) {System.out.println("華為手機(jī)適配電壓5伏");if(adapter.output5V()==5) System.out.println("華為手機(jī)充電成功");else System.out.println("華為手機(jī)充電不成功");}
}
package Adapter.Class;public interface Phone {public void charging(Adapter adapter);
}
package Adapter.Class;public interface Power5V {public int output5V();
}
package Adapter.Class;public class Power220V {private int power = 220;public int output220V() {System.out.println("電壓" + power + "伏");return power;}
}
這種模式被稱作類模式,可以看到Adapter繼承了Adaptee(要適配者)并且實(shí)現(xiàn)了Target(要適配者)。對(duì)于一對(duì)一的適配還有一種模式叫對(duì)象模式,在這種模式下,Adaptee會(huì)作為Adapter的成員屬性而不是讓Adapter去繼承Adaptee。
對(duì)象模式?
?
package Adapter.Object;public class Adapter implements Power5V {Power220V power220V;public Adapter() {}public Adapter(Power220V power220V) {this.power220V = power220V;}@Overridepublic int output5V() {int input = power220V.output220V();int output = input/44;return output;}
}
package Adapter.Object;public class Client {public static void main(String[] args) {Phone phone = new HuaWei();phone.charging(new Adapter(new Power220V()));}
}
?
雙向模式
上面的案例介紹了一對(duì)一的適配,還有一種適配是雙向的。下面用一個(gè)案例介紹:實(shí)現(xiàn)貓學(xué)狗叫和狗學(xué)貓抓老鼠。
package Adapter.BothWay;public class Adapter implements CatImpl,DogImpl{private CatImpl cat;private DogImpl dog;public CatImpl getCat() {return cat;}public void setCat(CatImpl cat) {this.cat = cat;}public DogImpl getDog() {return dog;}public void setDog(DogImpl dog) {this.dog = dog;}@Overridepublic void catchMice() {System.out.print("狗學(xué)");cat.catchMice();}@Overridepublic void cry() {System.out.print("貓學(xué)");dog.cry();}
}
package Adapter.BothWay;public class Cat implements CatImpl{@Overridepublic void catchMice() {System.out.println("貓抓老鼠");}@Overridepublic void cry() {}
}
package Adapter.BothWay;public interface CatImpl {public void catchMice();public void cry();
}
package Adapter.BothWay;public class Dog implements DogImpl{@Overridepublic void cry() {System.out.println("狗叫");}@Overridepublic void catchMice() {}
}
package Adapter.BothWay;public interface DogImpl {public void cry();public void catchMice();
}
package Adapter.BothWay;public class Client {public static void main(String[] args) {Adapter adapter = new Adapter();CatImpl cat = new Cat();DogImpl dog = new Dog();adapter.setCat(cat);adapter.setDog(dog);cat = (CatImpl) adapter;cat.cry();dog = (DogImpl) adapter;dog.catchMice();}
}