1. 程式人生 > 其它 >面試沒說清楚的design pattern(結構型模式)

面試沒說清楚的design pattern(結構型模式)

技術標籤:學習筆記designjava設計模式

學習目標:

常用的幾種design pattern
利弊分別是什麼?
具體舉個例子?


學習內容:

結構型模式:
1、 介面卡模式adapter
2、 橋接模式bridge
3、 動態代理模式dynamic proxy
行為型模式:
1、面試被問到observer是什麼模式?

學習時間:

1、 週一至週五晚上 7 點—晚上9點

學習產出:

1、 視訊10+個 2、技術筆記 3 篇

1.介面卡模式adapter

繼承的方式實現介面卡

package com.kuang.adapter;
//介面 轉換器的抽象實現
//網線插到轉化器上
public
interface NetToUsb { void handleRequest(); }
//網線
public class Adaptee {
    public void request(){
        System.out.println("連線網線上網");
    }
}
//1。繼承的方式,實現介面卡
//連線網線,連線usb
public class Adapter extends Adaptee implements NetToUsb{

    @Override
    public void handleRequest() {
        super
.request();//可以上網了 } }
//client class
public class ClientComputer {
     //電腦連上轉接器,才可以上網
     public void connectNet(NetToUsb adapter){
          adapter.handleRequest();
     }

     public static void main(String[] args) {
          ClientComputer clientComputer = new ClientComputer();//電腦
          Adaptee adaptee=
new Adaptee();//網線 Adapter adapter=new Adapter();//介面卡 clientComputer.connectNet(adapter);//電腦連上介面卡 } }

稍作修改,組合的方式實現介面卡

//2。組合方式,實現介面卡
//連線網線,連線usb
public class Adapter2 implements NetToUsb{
    private Adaptee adaptee;
//constructor
    public Adapter2(Adaptee adaptee) {
        this.adaptee = adaptee;
    }

    @Override
    public void handleRequest() {
        adaptee.request();//可以上網了
    }
}

區別:介面卡(adapter2)一端連電腦(clientComputer),一端連網線(adaptee)

//client class
public class ClientComputer {
     //電腦連上轉接器,才可以上網
     public void connectNet(NetToUsb adapter){
          adapter.handleRequest();
     }

     public static void main(String[] args) {
          ClientComputer clientComputer = new ClientComputer();//電腦
          Adaptee adaptee=new Adaptee();//網線
          Adapter2 adapter2=new Adapter2(adaptee);//2.介面卡連線網線
          clientComputer.connectNet(adapter2);//介面卡連上電腦
     }
}

優點:介面卡可以將多條功能線路,適配到同一個目標介面。
既然可以轉換網線,那麼再來一條網線的子類,也是可以適配的。
因此,符合裡式替換原則,拓展性比較好。
缺點:目標介面只能為介面,不能為類,這點具有一定的侷限性。

2.橋接模式bridge

也成為handle & body模式,或者interface模式。專門處理多維度獨立變化的情況。
下面例子中,父類/抽象類為橋樑,品牌和型別可以實現自由組裝。
蘋果+桌上型電腦
聯想+筆記本

視訊:橋接模式

public interface Brand {
    void info();
}
public class Apple implements Brand{
    @Override
    public void info() {
        System.out.print("Apple");
    }
}
public class Lenovo implements Brand{
    @Override
    public void info() {
        System.out.print("Lenovo");
    }
}
public abstract class Computer {
    //組合方式,自帶brand
    protected Brand brand;//子類繼承父類,還能用到

    public Computer(Brand brand) {
        this.brand = brand;
    }

    public void info() {
        brand.info();
    }
}

class Destop extends Computer{

    public Destop(Brand brand) {
        super(brand);
    }

    @Override
    public void info() {
        super.info();
        System.out.print("Destop");
    }
}
class Laptop extends Computer {

    public Laptop(Brand brand) {
        super(brand);
    }

    @Override
    public void info() {
        super.info();
        System.out.print("Laptop");
    }
}
public class Test {
    public static void main(String[] args) {
        Computer computer=new Laptop(new Apple());
        computer.info();

        Computer computer2=new Destop(new Lenovo());
        computer2.info();
    }
}

output:

AppleLaptop
LenovoDestop

如果想拓展,比如增加一個Tablet型別,組合起來也很方便。


class Tablet extends Computer {
    public Tablet(Brand brand) {
        super(brand);
    }

    @Override
    public void info() {
        super.info();
        System.out.print("Tablet");
    }
}
Computer computer3=new Tablet(new Lenovo());
        computer3.info();

output:

LenovoTablet

3.代理模式proxy

靜態代理 static proxy
不改變原有的程式碼情況下,另外設定proxy,在proxy裡改動和拓展功能。

package com.demo.kuangshen.demo;

public interface Rent {
   public void rent();
}
public class Host implements Rent{
   @Override
   public void rent() {
       System.out.print("房東要出租房子");
   }
public class Client {
   public static void main(String[] args){
       //房東要出租房子
       Host host=new Host();
//        host.rent();
       //代理,中介幫房東租房子,一般代理有附屬操作
       Proxy proxy=new Proxy(host);
       //不用面對房東,直接找中介租房
       proxy.rent();//背後還是host.rent()
   }
}
//代理幫房東
//引入房東組合,
//實現Rent介面
public class Proxy implements Rent{
   private Host host;
   public Proxy(){

   }
   public Proxy(Host host) {
       this.host = host;
   }

   @Override
   public void rent() {
       host.rent();
   }

   //看房
   public void seeHouse() {
       System.out.print("proxy帶你看房");
   }
   //籤合同
   public void sign() {
       System.out.print("proxy帶你籤合同");
   }
   //收中介費
   public void charge() {
       System.out.print("proxy收中介費");
   }
}

動態代理 dynamic proxy
動態代理的底層都是反射 reflection

package com.demo.kuangshen.demo.Demo3;

public interface Rent {
   public void rent();
}
public class Host implements Rent {
   @Override
   public void rent() {
       System.out.print("房東要出租房子");
   }
}

呼叫reflect包,用invoke來執行方法。

//用這個類,自動生成代理類
public class ProxyInvocationHandler implements InvocationHandler {
   //被代理的介面
   private Rent rent;//不同之處:這裡是被代理的介面,而不是host

  //生成得到代理類
   public Object getProxy() {
       //getClassLoader,interface,invocationHandler
       System.out.println("這是什麼?"+this); //[email protected]
//生成動態代理例項
       return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
   }

//處理代理例項,並返回結果
   @Override
   public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
       //reflect包下的method,   |執行介面的方法,引數
       seeHouse();
       Object res=method.invoke(rent,args);//用invoke來執行方法
       charge();
       return res;
       //動態代理的本質,就是使用反射機制實現
   }

   public void setRent(Rent rent) {
       this.rent=rent;
   }

   public void seeHouse() {
       System.out.println("帶房子");
   }
   public void charge() {
       System.out.println("收中介費");
   }
}

呼叫:

public class Client {
   public static void main(String[] args){
       //真實房東--要出租房子
       Host host=new Host();

       //代理角色,現在沒有
       ProxyInvocationHandler pih=new ProxyInvocationHandler();

       //通過invocationHandler,處理要呼叫的介面的物件(代理),
       pih.setRent(host);

       Rent proxy=(Rent) pih.getProxy();//
       proxy.rent();
   }
}
   //1。 ProxyInvocationHandler pih
   //2。 通過pih得到一個 proxy
   //3。實現房東要出租房子原始目的

行為型模式:

1.觀察者模式observer

模式類似SNS服務,訂閱者subscribe了一個主題/訊息源,訊息源一旦釋出訊息,訂閱者就會收到通知。
定義一對多的關係。當一個物件改變狀態,依賴它的物件都會收到通知,並自動更新。
設計模式:觀察者模式
張三和趙四王五借錢,承諾有錢還了就通知他們:
具體目標物件和具體觀察者物件之間不能直接呼叫,否則將使兩者之間緊密耦合起來,違反了面向物件的設計原則。
zhangsan通過Borrower介面 notifyLenders ()
lisi,wangwu通過Lender介面 takeMoney()

package com.kuang.observer;

import java.util.ArrayList;
import java.util.List;

public class ObserverPattern {
    public static void main(String[] args) {
        Borrower zhangsan=new Zhangsan();
        zhangsan.borrow(new Zhaosi());
        zhangsan.borrow(new Wangwu());
        //一旦狀態改變,有錢了,通知多人:
        zhangsan.notifyLenders();
    }
}

interface Borrower{
    void borrow(Lender lender);
    void notifyLenders();
}

class Zhangsan implements Borrower{
    private List<Lender> allLenders=new ArrayList<>();
   // private int state=0;//1是有錢
    @Override
    public void borrow(Lender lender) {
        allLenders.add(lender);
    }

    @Override
    public void notifyLenders() {
        allLenders.forEach(lender->lender.takeMoney());
    }
}
interface Lender{
    void takeMoney();
}
class Zhaosi implements Lender{
    @Override
    public void takeMoney() {
        System.out.println("趙四要錢");
    }
}

class Wangwu implements Lender{
    @Override
    public void takeMoney() {
        System.out.println("王五要錢");
    }
}
趙四要錢
王五要錢

優點:
1.降低了目標與觀察者之間的耦合關係,兩者之間是抽象耦合關係。符合依賴倒置原則。
2.目標與觀察者之間建立了一套觸發機制。
缺點:
1.目標與觀察者之間的依賴關係並沒有完全解除,而且有可能出現迴圈引用。
2.當觀察者物件很多時,通知的釋出會花費很多時間,影響程式的效率。

Thank you for reading !
Alt