关于工厂模式的问题,急急急急急急!!

dengjian008 2004-05-02 01:31:01
通过工厂的接口可以拿到工厂的产品,可是如果有多个产品,他们又都有自己独有的方法,我又想只用一个接口拿到这些产品,可接口中只能写这些产品共有的方法。请问在工厂模式中如何才能用接口拿到每个产品所有的方法呢(共有的和自己独有的)?
...全文
63 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
panpan221 2004-05-02
  • 打赏
  • 举报
回复
新手学习
bluesage 2004-05-02
  • 打赏
  • 举报
回复
作类型向下转换,如果达不到你想要的目的,那么得考虑重新抽象设计了。
sean_gao 2004-05-02
  • 打赏
  • 举报
回复
public class TestFactory {

public static IProduct getProduct(int id) {
if (id>0) return new ProductA(id);
else return new ProductB();
}

public static void main(String[] args) {
IProduct p1 = getProduct(165);
IProduct p2 = getProduct(0);
p1.showYourID();
p2.showYourID();
((ProductA)p1).showProductAStatus();
((ProductB)p2).showProductBStatus();
}
}

interface IProduct {
public void showYourID();
}

class ProductA implements IProduct {
private int id;
ProductA(int id) { this.id=id; }
public void showYourID() {
System.out.println("This product has the following id: "+ id+".");
}
public void showProductAStatus() {
System.out.println("This is of ProductA type.");
}
}

class ProductB implements IProduct {
public void showYourID() {
System.out.println("This product has no ID.");
}
public void showProductBStatus() {
System.out.println("This is of ProductB type.");
}
}
dengjian008 2004-05-02
  • 打赏
  • 举报
回复
请回帖的各位举例说明!!!!!!!!!!!!!!多谢了

51,397

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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