java設(shè)計模式

eg.png
| 插座的比喻 | 實例程序 | |
|---|---|---|
| 需求 | 兩孔插座 | Two接口 |
| 交換裝置 | 適配器 | Adapter類 |
| 實際接口 | 三孔插座 | Three接口 |
| 實際實現(xiàn) | 三孔實現(xiàn)類 | Three類 |
類適配器模式(使用繼承)
接口A中沒有我們想要的方法 ,接口B中有合適的方法,不能改變訪問接口A
定義一個適配器p:繼續(xù)訪問當(dāng)前接口A中的方法
p繼承接口B的實現(xiàn)類BB : 可以在適配器P中訪問接口B的方法
在適配器P中的接口A方法中直接引用BB中的合適方法
//Two接口Ithree:
public interface Ithree{
void isthree();
}
//Three接口Itwo:
public interface Itwo{
void istwo();
}
//Ithree接口的實現(xiàn)類
public class Three implements Ithree{
@Override
public void isthree() {
System.out.println("Three");
}
}
//適配器adapter
public class Adapter extends Three implements Itwo {
@Override
public void istwo() {
isthree();
}
}
//測試方法:Clienter
public class Clienter {
public static void main(String[] args) {
Two two = new Adapter();
two.istwo();
}
}
對象適配器模式
要訪問的接口A中沒有想要的方法 ,卻在接口B中發(fā)現(xiàn)了合適的方法,接口A不能改變
定義一個適配器p:作用:實現(xiàn)我們訪問的接口A
P中定義私有變量C(對象)(B接口的實現(xiàn)類)
再定義一個帶參數(shù)的構(gòu)造器用來為對象C賦值
再在A接口的方法實現(xiàn)中使用對象C調(diào)用其來源于B接口的方法。
//Two接口Ithree:
public interface Ithree{
void isthree();
}
//Three接口Itwo:
public interface Itwo{
void istwo();
}
//Ithree接口的實現(xiàn)類
public class Three implements Ithree{
@Override
public void isthree() {
System.out.println("Three");
}
}
//適配器adapter
public class Adapter implements Itwo {
private Three three;
public Adapter(Three three){
this.three = three;
}
@Override
public void istwo() {
three.isthree();
}
}
//測試方法:Clienter
public class Clienter {
public static void main(String[] args) {
Two two = new Adapter();
two.istwo();
}
}
接口適配器模式
當(dāng)存在這樣一個接口,其中定義了N多的方法,卻只想使用其中的一個到幾個方法,如果我們直接實現(xiàn)接口,那么我們要對所有的方法進(jìn)行實現(xiàn),哪怕我們僅僅是對不需要的方法進(jìn)行置空(只寫一對大括號,不做具體方法實現(xiàn))也會導(dǎo)致這個類變得臃腫,調(diào)用也不方便
使用一個抽象類作為中間件——適配器:實現(xiàn)接口,抽象類中所有的方法都進(jìn)行置空
再創(chuàng)建抽象類的繼承類
重寫我們需要使用的那幾個方法
//目標(biāo)接口A
public interface A {
void a();
void b();
void c();
void d();
void e();
void f();
}
//適配器:Adapter
public abstract class Adapter implements A {
public void a(){}
public void b(){}
public void c(){}
public void d(){}
public void e(){}
public void f(){}
}
//實現(xiàn)類:Asuccess
public clall Asuccess extends Adapter{
public void a(){
System.out.println("實現(xiàn)A方法被調(diào)用");
}
}
//測試類
public class Clienter {
public static void main(String[] args) {
A a = new Ashili();
a.a();
a.d();
}
}
總結(jié)

adapter.png