對象具體還是抽象?

在開發中,我們經常會把變量設置爲私有(private),不想使用者依賴這些變量,但很多程序員也會給對象自動添加get/set方法,將私有變量公之於衆。
具體點

public class User {
    private int userId;
    private String userName;
}

抽象點

public interface User {
    int getUserId();

    String getUserName();

    void setUser(int userId, String userName);
}

抽象點優勢在於使用者不知道該User信息是如何實現的,並明白無誤地呈現了一種數據結構;而具體點暴露了具體實現,即便是私有變量,通過get/set還是會暴露具體實現。
所以隱藏實現不是單單的把變量之間放上一個函數層那麼簡單。隱藏實現關乎於抽象,類並不簡單地用get/set將變量推向外間,而是暴露抽象接口,以便使用者無需瞭解數據的實現就能操作數據本地。
當然在具體實現中,這種並不是絕對的,對象和數據結構有相關的反對稱性。
過程式代碼

public class PercentDiscount {
    private float percent;
    private float price;
}


public class ReductionDiscount {
    private float reduction;
    private float price;
}

public class Discount {

    public float getPrice(Object obj) throws NoSuchFieldException {
        if (obj instanceof PercentDiscount) {
            PercentDiscount pd = new PercentDiscount();
            return pd.percent * pd.price;
        } else if (obj instanceof ReductionDiscount) {
            ReductionDiscount rd = new ReductionDiscount();
            return rd.price - rd.reduction;
        } else {
            throw new NoSuchFieldException();
        }

    }
}

多態式代碼

public class PercentDiscount implements Discount {
    private float percent;
    private float price;

    @Override
    public float getPrice() {
        return price * percent;
    }
}


public class ReductionDiscount implements Discount {
    private float reduction;
    private float price;

    @Override
    public float getPrice() {
        return price - reduction;
    }
}

public interface Discount {
    float getPrice();
}

我們看到這兩種定義的本質是截然對立的。過程式代碼便於在不改動既有數據結構的前提下添加新函數,而面向對象代碼便於在不改動既有的函數下添加新類。
所以在具體的業務場景在來決定使用哪種方式,需要添加新數據類型而不是新函數的時候可以使用面向對象;需要添加新函數而不是數據類型使用過程式比較合適。一切都是對象只是一個傳說。具體的使用方式需要根據當前業務場景來決定。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章