JAVA接口的應用及工廠模式的簡單示例

背景:開發一臺打印機程序,能控制三臺(可能會增加至一百臺)打印機,每臺打印機都有最基本的開機、打印、關機三個功能,且三個功能的實現都不相同。


建立打印機接口

interface Printer{
	public void open();
	
	public void print(String s);
	
	public void close();
}

分別建立三臺打印機

class HPPrinter implements Printer{
	public void open(){
		System.out.println("HP open");
	}
	
	public void print(String s){
		System.out.println("HP print:"+s);
	}
	
	public void close(){
		System.out.println("HP close");
	}
}

class CanonPrinter implements Printer{
	public void open(){
		System.out.println("Canon open");
	}
	
	public void print(String s){
		System.out.println("Canon print:"+s);
	}
	
	public void close(){
		System.out.println("Canon close");
	}
}

class SonyPrinter implements Printer{
	public void open(){
		System.out.println("Sony open");
	}
	
	public void print(String s){
		System.out.println("Sony print:"+s);
	}
	
	public void close(){
		System.out.println("Sony close");
	}
}

建立打印機工廠(如果以後程序需要新增打印機,只需在此添加)

class PrinterFactory{
	public static Printer getPrinterFactory(int flag){
		Printer printer=null;
		
		if (flag==0){
			printer=new HPPrinter();
		}
		else if(flag==1){
			printer=new CanonPrinter();
		}
		else if(flag ==2){
			printer=new SonyPrinter();
		}
		
		return printer;
	}
}

建立主函數

class Test{
	public static void main(String args[]){
		int flag=2;
		Printer printer=PrinterFactory.getPrinterFactory(flag);
		printer.open();
		printer.print("Derek up");
		printer.close();
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章