19.接口的应用

  • 为什么要使用接口?
 
  • 工厂方法模式
    • 使用了接口,静态函数,向上转型
    • 思路:使用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
 





posted @ 2016-08-28 17:22  ArronEve  阅读(91)  评论(0编辑  收藏  举报