1. 深入理解適配器模式
1.1 適配器模式的理念:提高兼容性,解耦
1.2 命題:
1 商人需要鋼,但是供貨商只能提供鐵,此時要怎樣得到自己的需求?(類的適配器模式)
1.1 創建供貨商
class tource {
public void method1() {
System.out.println("this is original method!");
}
}
1.2 定義你想要得到的鋼,以及鍊鋼方式
// 你的目標
interface targatable{
public void method1();
public void method2();
}
// 適配器
class Adapter extends tource implements targatable {
@Override
public void method2() {
System.out.println("this is the targetable method!");
}
}
1.3 拿到鋼
public class source{
public static void main(String[] args) {
targatable target = new Adapter();
target.method1();
target.method2();
}
}
2 商人覺得自己做事太死板,想靈活一點,商人怎樣達到自己的需求?(對象的適配器模式)
2.1 創建供貨商
class aource {
public void method1() {
System.out.println("this is original method!");
}
}
2.2 定義你想要得到的鋼,以及鍊鋼方式
interface aargatable{
public void method1();
public void method2();
}
// 適配器
class aadapter implements aargatable {
private aource aou;
public aadapter(aource source){
this.aou = source;
}
public void method2() {
System.out.println("this is the targetable method!");
}
public void method1() {
aou.method1();
}
}
2.3 拿到鋼
public class source2 {
public static void main(String[] args) {
aource source = new aource();
aargatable target = new aadapter(source);
target.method1();
target.method2();
}
}
3 商人賺了錢,覺得以上方式固然拿到了鋼,但是覺得還是不夠靈活,總是讓我提供某以方面,何不綜合利用一下,供貨商有鐵,商人提供鍛造的渠道,鍛造渠道的人來找商人,商人提供鐵,這樣就能物盡所用(接口的適配器模式:多減少補)
3.1 商人定義目標並定義配合方式
interface Sourceable {
public void method1();
public void method2();
}
// 定義抽象類,實現該接口
abstract class Wrapper2 implements Sourceable{
public void method1(){}
public void method2(){}
}
3.2 很多供貨商看到了配合方式,覺得自己有例可圖,都聯繫上商人
// 重寫抽象類
class SourceSub1 extends Wrapper2 {
public void method1(){
System.out.println("the SourceSub1's first Sub1!");
}
}
class SourceSub2 extends Wrapper2 {
public void method2(){
System.out.println("the SourceSub2's second Sub2!");
}
}
3.3 拿到鋼
public class source3 {
public static void main(String[] args) {
Sourceable source1 = new SourceSub1();
source1.method1();
source1.method2();
Sourceable source2 = new SourceSub2();
source2.method1();
source2.method2();
}
}
2.適配器模式運用的場合
2.1 你想漲薪水,除了自身的努力外,你需要時間和知識,你覺得自己夠努力,知識也能在互聯網找到,但是你總是加班,這種情況下你還是考慮下怎麼調整
2.2 多減少補(這個很厲害的)