标签:
interface Printer{
publicvoid open();
publicvoid close();
publicvoid print(String s);
}
classHPPrinter implements Printer{
publicvoid open(){
System.out.println("HP open");
}
publicvoid close(){
System.out.println("HP close");
}
publicvoid print(String s){
System.out.println("HP print---->"+ s);
}
}
classCanonPrinter implements Printer{
privatevoid clean(){
System.out.println("clean");
}
publicvoid close(){
this.clean();
System.out.println("Canon close");
}
publicvoid open(){
System.out.println("Canon open");
}
publicvoid print(String s){
System.out.println("Canon print---->"+ s);
}
}
classPrinterFactory{
publicstaticPrinter getPrinter(int flag){
Printer printer = null;
if(flag ==0){
printer =newHPPrinter();
}
elseif(flag ==1){
printer =newCanonPrinter();
}
return printer;
}
}
classTest{
publicstaticvoid main(String args []){
//根据用户的选择,生成相应的打印机对象
//并且向上转型为Printer类型
//Printer getPrinter(int flag)
int flag =0;
Printer printer =PrinterFactory.getPrinter(flag);
printer.open();
printer.print("test");
printer.close();
}
}
标签:
原文地址:http://www.cnblogs.com/arroneve/p/5815458.html