码迷,mamicode.com
首页 > 移动开发 > 详细

mars老师java4android接口实例

时间:2014-09-09 20:02:09      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:android   style   blog   color   os   java   ar   div   sp   

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接口实例

标签:android   style   blog   color   os   java   ar   div   sp   

原文地址:http://www.cnblogs.com/catcher-1224/p/3963195.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!