首页 > 代码库 > mars老师java4android接口实例
mars老师java4android接口实例
1.创建一个Printer接口
interface Printer{ public void open(); public void print(String s); public void close();}
2.创建一个PrinterFactory类
public class PrinterFactory{ public static Printer getPrinter(int flag){ Printer printer = null; if(flag == 0){ printer = new HPPrinter(); }else if(flag == 1){ printer = new CanonPrinter(); }else if(flag == 2){ printer = new XXXPrinter(); } return printer; }}
3.创建HPPrinter类
class HPPrinter implements Printer{ public void open(){ System.out.println("HPPrinter open"); } public void print(String s){ System.out.println("HPPrinter print--->" + s); } public void close(){ System.out.println("HPPrinter close"); }}
4.创建CanonPrinter类
class CanonPrinter implements Printer{ private void clean(){ System.out.println("CanonPrinter clean"); } public void close(){ this.clean(); System.out.println("CanonPrinter close"); } public void open(){ System.out.println("CanonPrinter open"); } public void print(String s){ System.out.println("CanonPrinter print--->" + s); }}
5.创建XXXPrinter类
public class XXXPrinter implements Printer{ public void open(){ System.out.println("XXXPrinter open"); } public void print(String s){ System.out.println("XXXPrinter print--->" + s); } public void close(){ System.out.println("XXXPrinter close"); }}
6.创建Test类
public class Test{ public static void main(String args[]){ int flag = 2; Printer printer = PrinterFactory.getPrinter(flag); printer.open(); printer.print("test"); printer.close(); }}
mars老师java4android接口实例
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。