《Head First Design Pattern》--开篇: 鸭子的故事
有各种各样的鸭子(酱鸭、板鸭、黑头鸭、野鸭、盐水鸭...),特征是Quack(嘎嘎叫),Swim(游水)。
于是定义的一个SuperDuck(父类),里面有方法Quack、Swim、Display显示!
子类比如黑头鸭、RedHeadDuck,重写Display方法!
But Now We need the ducks to Fly!
How to do?
(鸭子要可以飞,怎么办?)
I Just need to add a fly() method in the SuperDuck(父类),then all the ducks will inherit it.
Now's my time to really show my true OO genius!(我真是个OO的天才啊,哈哈!)
They just give a demo and there were rubber duckies flying around the screen!
Was this idea of a joke?
(他们只不过做了一个让好多橡皮的鸭子满屏幕飞的演示!
(他们只不过做了一个让好多橡皮的鸭子满屏幕飞的演示!
这是在开玩笑吗?)
不是所有的鸭子都能飞的呀!!!
Thinks about inheritance(考虑一下继承)
我可以在RubberDuck(橡皮鸭)中重写Fly的方法。
But then what happens when wu add wooden decoy ducks(木头鸭),它既不能Quack叫,也不能Fly。
在木头鸭重写Quack()、Fly()????
How about a interface?
I could take the fly() out of the SuperDuck(父类),and make a flyable() interface with a fly() method. That way,only the ducks that are supposed to fly will implement that interface and have a fly() method....and I might as well make a Quackable(嘎嘎),too,since not all the ducks can quack!
(接口怎么样?
我可以把Fly从父类中剥离出来,变成一个接口,如果有鸭子可以飞,那么这只鸭子就实现这个接口。 Quack(嘎嘎叫)也是类似的.)
That is , like , the dumbest idea you've come up with.Can you say "duplicate code"?If you thought having to override a few methods was bad,How are you gonna feel when you need to make a little change to the flying behavior... in all 48 of the flying Duck subclass?!
(现在你可以说copy代码。那么我们如果对flying 有一个小小的改变怎么样?所有48个用到这个接口的子类都要改变一下,Copy48份?????)
How we can do next???
到底该怎么办?
Please be with <<Head First Design pattern>>!