java 接口工厂_[Java教程]接口的应用和工厂方法模式

[Java教程]接口的应用和工厂方法模式

0 2014-11-03 23:02:18 interface Printer{public void open();public void close();public void print(String s);}

class HP implements Printer{public void open(){System.out.println("惠普打印机开机");}public void print(String s){System.out.println(s);}private void clean(){System.out.println("清洗");}public void close(){this.clean();System.out.println("惠普打印机关机");}}

class Canon implements Printer{public void open(){System.out.println("佳能打印机开机");}public void print(String s){System.out.println(s);}public void close(){System.out.println("佳能打印机关机");}}

class PrintFactory{public static Printer getPrinter(int flag){//根据用户所选择的打印机生成相应的打印机对象并向上转型为Printer类型Printer printer = null;if(flag == 1){printer = new HP();}else{printer = new Canon();}return printer;}}

class test{public static void main(String args[]){int flag = 0;Printer p = PrintFactory.getPrinter(flag);p.open();p.print("test");p.close();}}

bc91bb04e6e9c61e24c974e4440db8f2.gif

Printer是接口,HP类和Canon类用来实现接口,生成HP和Canon两个类的对象的代码封装在PrintFactory的getPrinter方法中。当需要生成打印机对象时,调用PrintFactory的getPrinter方法。好处在于:在一个大系统中生成对象使用打印机的功能时减少重复代码,使用者并不需要知道打印机的种类,同时也方便开发者修改打印机的种类

本文网址:http://www.shaoqun.com/a/103743.html

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:admin@shaoqun.com。

接口

0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值