[英]Why to use nested class in builder design pattern, why can't use setters to build the object in the same class
[英]Why the Class Adapter Design Pattern Can't Use an Interface Instead of Multiple Inheritance?
我最近學習了 Class 適配器模式。 為了實現它,使用的語言必須支持多個 inheritance,因為適配器 class 必須繼承兩個類,Target 和 Adaptee。 所以在像 Java 這樣的語言中,它是做不到的。
但是為什么它不能使用接口 Target 而不是 class Target? 更符合 Object 適配器模式。 只需從 object 組合(Adapter 具有 Adaptee)切換到單個 inheritance(Adapter 繼承 Adaptee)。 通過使用接口,我沒有看到設計差異,因此,該模式可以在 Java 中使用。
但是為什么它不能使用接口 Target 而不是 class Target?
你可以使用界面。 但是你會有重復的代碼,但是多個 inheritance 會刪除重復的代碼。
讓我舉個例子。
我們的抽象:
public interface IDuck
{
void Quack();
}
public interface ITurkey
{
void Gobble();
}
以及具體的實現:
public class Duck : IDuck
{
public void Quack()
{
Console.WriteLine("Quack");
}
}
public class Turkey : ITurkey
{
public void Gobble()
{
Console.WriteLine("Gobble");
}
}
class 適配器看起來像這樣:
public class ClassAdapter : IDuck, ITurkey
{
public void Gobble()
{
// duplication of code
Console.WriteLine("Gobble");
}
public void Quack()
{
Gobble();
}
}
上面的ClassAdapter
有重復的代碼。 當然,我們可以提取此代碼並通過組合或注入 Duck 和土耳其來提供它。 然而,它帶來了額外的依賴和一些復雜性。 所以最好使用 object 適配器模式。 你的代碼會更簡單。 簡單的代碼幾乎總是最好的選擇。
通常沒有理由不能在 Java 的兩個接口之間創建 Class 適配器。 但首先你必須足夠幸運,能夠在需要調整的兩個 API 都是接口的情況下開始。
適配器主要用於彌合不屬於您的兩個現有 API 之間的差距。 如果您控制一個或兩個 API,您可以簡單地更改一個以匹配另一個。 當您需要兩個獨立的 API 來兼容,但這些 API 不屬於您時,那么您必須調整給定的內容,這可能不是接口。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.