Re: [閒聊] OOP小評
※ 引述《csfgsj (Lazy bone)》之銘言:
: 開放體系就是在我得到這雙鞋子時
: Struct Shoes {…..}
: 我不必去預先設定我會對它作什麼動作
: 對鞋子的動作可能當時有一些
: A( shoes *);
: 以後有可能再去想到另外一些
: B( shoes *)
: 我不用一開始就把所有東西都設死
我也想玩了。但我不太喜歡 OOP 雖然必要時都會使用,所以我的 Java 碼可能寫得
比較爛一點,看看。
interface ShoeI { }
class Shoe implements ShoeI {
private float _height;
private String _color;
}
以上一樣是「不必去預先設定鞋子該有什麼動作」。
接著當我需要高根鞋類別的時候,並不像你的 struct Shoes { ... } 需要
copy & paste 然後改成 struct highheels { ... } 而且連裡面的欄位都改,
而是增加一個繼承 Shoe 的類別:
class Highheel extends Shoe implements ShoeI { }
而且在 Highheel 類別中,什麼都不必寫。所以在此並沒有你所說的「 class 為
萬惡之源」吧。
***
接著,我要開始想,在鞋子裡要有一些什麼了,所以介面就改了。
interface ShoeI {
public float height();
public String color();
public void put_on(Animal);
}
所以,實作介面的類別要被逼著一起加東西:
class Shoe implements ShoeI {
private float _height;
private String _color;
public Shoe(float height, String color) {
this._height = height;
this._color = color;
}
public float height() { return this._height; }
public String color() { return this._color; }
public put_on(Animal animal) {
animal.wear(this);
}
}
class Highheel extends Shoe {
public Highheel(float height, String color) {
super();
this._height += 10;
}
}
interface AnimalI { public void wear(Shoe) throws NoFootException; }
class Animal {
private int _foot_num;
private int _shoe_num = 0;
private String _name;
private float _height;
private float _max_shoe_height = 0;
public Animal(int foot_num, String name, float height) {
this._foot_num = foot_num;
this._name = name;
this._height = height;
}
public void wear(Shoe shoe) throws NoFootException {
if (this._shoe_num < this._foot_num) {
this._foot_num ++;
if (this._max_shoe_height < Shoe.height())
this._max_shoe_height = Shoe.height();
System.out.println("I " + this._name + " put on a shoe of"
+ Shoe.color() + " and " + Shoe.height()
+ " cm.");
}
System.out.println("Now I\'m " + (this._height
+ this._max_shoe_height) + " tall.");
if (this._shoe_num >= this._foot_num) {
System.out.println("Though I have too few feets to wear the"
+ " new " + Shoe.color() + " shoe.");
throw new NoFootException();
}
}
}
你看,穿普通鞋與穿高根鞋的動作是一模一樣,所以我沒有 copy & paste ;
普通鞋與高根鞋的「性:顏色」、「量:高度」都是一樣的方法,我也沒有
copy & paste 。
***
我用了 class ,但是,沒有 copy & paste 也沒有不定性定量,而且也不隱晦。
當然你可以說我沒有考慮到脫鞋的情況,也算是尚未有效定性定量,
但是,我覺得應該把話講清楚,我是「尚未」有效定性定量,
而不是這些 domain 「不能」藉由 class 有效定性定量。
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 118.160.144.227
※ 文章網址: https://www.ptt.cc/bbs/Soft_Job/M.1425571334.A.B57.html
→
03/06 00:07, , 1F
03/06 00:07, 1F
→
03/06 00:10, , 2F
03/06 00:10, 2F
→
03/06 00:11, , 3F
03/06 00:11, 3F
※ 編輯: yauhh (118.160.144.227), 03/06/2015 00:18:19
→
03/06 01:41, , 4F
03/06 01:41, 4F
討論串 (同標題文章)
本文引述了以下文章的的內容:
閒聊
1
26
以下文章回應了本文:
閒聊
2
31
完整討論串 (本文為第 34 之 43 篇):
閒聊
3
26
閒聊
0
2
閒聊
1
2
閒聊
6
21
閒聊
3
5
閒聊
1
1
閒聊
-8
31
閒聊
3
4
閒聊
1
5
閒聊
6
17