设计模式——消除重复代码

qlboob 2009-06-20 09:11:11
加精

public class Car
{
//some methods
}

public class CarA extends Car
{
public void pop()
{
System.out.println("pop");
}
//other methods
}

public class CarB extends Car
{
public void pop()
{
System.out.println("pop");
}
//other methods
}



请问在不修改Car类的情况下,如何消除CarA&CarB重复的方法pop?我感觉下面的这种方法不爽,请达人指点


public class Car
{
//some methods
}

public class CarM extends Car
{
public void pop()
{
System.out.println("pop");
}
//other methods
}


public class CarA extends CarM
{
//other methods
}

public class CarB extends CarM
{
//other methods
}


...全文
435 40 打赏 收藏 转发到动态 举报
写回复
用AI写文章
40 条回复
切换为时间正序
请发表友善的回复…
发表回复
soulx 2009-07-08
  • 打赏
  • 举报
回复
我觉得这要看你的pop方法对Car来说的意图是什么:

1.如果pop是Car的固有行为的话,那么把pop写到Car或者用抽象工厂都可以。

2.如果pop只是Car的一种辅助功能的话,那么用组合模式就可以。
彷徨的蜗牛 2009-07-08
  • 打赏
  • 举报
回复
public class Car
{
//some methods
}

interface CarFactory{
void pop();
}

public class CarA extends Car implements CarFactory
{
public void pop()
{
System.out.println("pop");
}
//other methods
}

public class CarB extends Car implements CarFactory
{
public void pop()
{
System.out.println("pop");
}
//other methods
}
wuzhongxing 2009-07-08
  • 打赏
  • 举报
回复
up
***!@#¥ 2009-07-08
  • 打赏
  • 举报
回复
学习了,谢谢各位达人。。。
heiqilin1985 2009-07-08
  • 打赏
  • 举报
回复
长见识了....汗...模试还没接触过..看大家讲的都挺新鲜的
grzx2210 2009-07-08
  • 打赏
  • 举报
回复
我觉得用 abstract Factory模式
加油馒头 2009-07-08
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 qusic 的回复:]
这个要看你的pop方法是不是有多个car的子类都在用了。如果有许多子类都有这个方法,
那为什么不把它提取到Car类里面呢?如果只有一两个类使用,那么重复了也未尝不可,
或者说使用你那种方法也行。
Java codepublicclassCar
{//some methodspublicvoidpop()
{
System.out.println("pop");
}
}publicclassCarAextendsCar
{//other methods}publicclassCarBextendsCar
{//other methods}publicclassCarCexten…
[/Quote]


这不错,比较适中
冰思雨 2009-07-08
  • 打赏
  • 举报
回复
public interface Car
{
//some methods
}

public abstract class PopCar
{
public void pop()
{
System.out.println("pop");
}
//other methods
}

public class CarA extends PopCar implements Car
{
//other methods
}

public class CarB extends PopCar implements Car
{
//other methods
}

楼主看看这样设计,是否符合要求?
elmnd 2009-07-08
  • 打赏
  • 举报
回复
倾向于5L大哥的思路
qp131420 2009-07-08
  • 打赏
  • 举报
回复
mark
xihucool 2009-07-08
  • 打赏
  • 举报
回复
学习一下
accp_huangxin 2009-07-07
  • 打赏
  • 举报
回复
建议用动态工厂模式去实现,
jokerdx 2009-07-07
  • 打赏
  • 举报
回复
学习了~~~~
郎岳樟 2009-07-07
  • 打赏
  • 举报
回复
实现方式蛮多 我也迷糊 但记得设计模式中建议 “少用继承” 我回去再翻翻书!!
huosidun0302 2009-07-07
  • 打赏
  • 举报
回复
学习
lsd123 2009-07-07
  • 打赏
  • 举报
回复
.
玖伍叁柒 2009-07-07
  • 打赏
  • 举报
回复
看见"设计模式"这四个字,我就想起了四人帮的写的那个<设计模式>来...
thumb3344 2009-07-07
  • 打赏
  • 举报
回复
11楼正解。
OpenFire_wpvsyou 2009-07-07
  • 打赏
  • 举报
回复
谢谢 楼主的分享!!!
OpenFire_wpvsyou 2009-07-07
  • 打赏
  • 举报
回复
haha 张见识了·
加载更多回复(19)

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧