首页 > 其他 > 详细

19.接口的应用

时间:2016-08-28 17:59:47      阅读:104      评论:0      收藏:0      [点我收藏+]
  • 为什么要使用接口?
 
  • 工厂方法模式
    • 使用了接口,静态函数,向上转型
    • 思路:使用new来调用构造函数的代码,把他封装在工厂类当中
    • 对于使用者来讲,只需要调用和修改工厂就可以了
 
  1. interface Printer{
  2. publicvoid open();
  3. publicvoid close();
  4. publicvoid print(String s);
  5. }
 
  1. classHPPrinter implements Printer{
  2. publicvoid open(){
  3. System.out.println("HP open");
  4. }
  5. publicvoid close(){
  6. System.out.println("HP close");
  7. }
  8. publicvoid print(String s){
  9. System.out.println("HP print---->"+ s);
  10. }
  11. }
 
  1. classCanonPrinter implements Printer{
  2. privatevoid clean(){
  3. System.out.println("clean");
  4. }
  5. publicvoid close(){
  6. this.clean();
  7. System.out.println("Canon close");
  8. }
  9. publicvoid open(){
  10. System.out.println("Canon open");
  11. }
  12. publicvoid print(String s){
  13. System.out.println("Canon print---->"+ s);
  14. }
  15. }
 
  1. classPrinterFactory{
  2. publicstaticPrinter getPrinter(int flag){
  3. Printer printer = null;
  4. if(flag ==0){
  5. printer =newHPPrinter();
  6. }
  7. elseif(flag ==1){
  8. printer =newCanonPrinter();
  9. }
  10. return printer;
  11. }
  12. }
 
  1. classTest{
  2. publicstaticvoid main(String args []){
  3. //根据用户的选择,生成相应的打印机对象
  4. //并且向上转型为Printer类型
  5. //Printer getPrinter(int flag)
  6. int flag =0;
  7. Printer printer =PrinterFactory.getPrinter(flag);
  8. printer.open();
  9. printer.print("test");
  10. printer.close();
  11. }
  12. }
 
结果:
D:\work\src>javac *.java
 
D:\work\src>java Test
HP open
HP print---->test
HP close
 





19.接口的应用

原文:http://www.cnblogs.com/arroneve/p/5815458.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!