浏览 1535 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2009-06-15
最后修改:2009-06-15
public abstract class Duck { public abstract void color(); public abstract void weight(); } RedDuck(红色的鸭子) public class RedDuck extends Duck { @Override public void color() { // TODO Auto-generated method stub System.out.println("I'M color is red"); } @Override public void weight() { // TODO Auto-generated method stub System.out.println("I'm weight is 5kg"); } } 颜色和重量是每个鸭子的共同特性,还有一个其他的特性比如飞行和叫有一个鸭子就不会,玩具鸭就不叫(假设),木头鸭就不会飞.所以我们把变化的东西组合到类里,不使用继承. 飞接口 public interface IFlyAction { public void fly(); } 叫接口 public interface IShoutAction { public void shout(); } 定制RedDuck飞的动作 public class RedDuckFly implements IFlyAction { @Override public void fly() { // TODO Auto-generated method stub System.out.println("i can fly"); } } 定制RedDuck的叫 public class RedDuckShout implements IShoutAction { @Override public void shout() { // TODO Auto-generated method stub System.out.println("g ,g,g"); } } public abstract class Duck { private IFlyAction flyAction; private IShoutAction shoutAction; public abstract void color(); public abstract void weight(); //所有的鸭子都会游泳 public void swim() { System.out.println("i cam swim"); } public void setFlyAction(IFlyAction flyAction) { this.flyAction = flyAction; } public void setShoutAction(IShoutAction shoutAction) { this.shoutAction = shoutAction; } public void performFly(){ flyAction.fly(); } public void performShout(){ shoutAction.shout(); } } 测试类 public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Duck redDuck = new RedDuck(); //可以动态的定制动作 redDuck.setFlyAction(new RedDuckFly()); redDuck.setShoutAction(new RedDuckShout()); redDuck.performFly(); } } 设计原则: 1.多用组合,少用继承 2.面象接口编程 3.是事物尽量的抽象化,提取共同特性 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |