接口的应用:
主要内容:
1.为什么要使用接口?
主要内容:
1.为什么要使用接口?
2.工厂方法模式。
interface Printer{
public void open();
public void close();
public void print(String s);
}
class HpPrinter implements Printer{
public void open(){
System.out.println("HP open");
}
public void close(){
System.out.println("HP close");
}
public void print(String s){
System.out.println("HP print --->" + s);
}
}
class CannoPrinter implements Printer{
public void close(){
this.clean();
System.out.println("Canon close");
}
private void clean(){
System.out.println("clean");
}
public void open(){
System.out.println("Canno open");
}
public void print(String s){
System.out.println("Canno print --->" + s);
}
}
class Test{
public static void main(String args[]){
Printer printer = null;
int flag = 1;
if(flag == 0){
printer = new HpPrinter();
}else if(flag == 1){
printer = new CannoPrinter();
} //这种方法会在这里出现问题,如果有100台以上的打印机就会很多
printer.open();
printer.print("test");
printer.close();
}
}
可以直接创建一个类来解决这个问题:
interface Printer{
public void open();
public void close();
public void print(String s);
}
class HpPrinter implements Printer{
public void open(){
System.out.println("HP open");
}
public void close(){
System.out.println("HP close");
}
public void print(String s){
System.out.println("HP print --->" + s);
}
}
class CannoPrinter implements Printer{
public void close(){
this.clean();
System.out.println("Canon close");
}
private void clean(){
System.out.println("clean");
}
public void open(){
System.out.println("Canno open");
}
public void print(String s){
System.out.println("Canno print --->" + s);
}
}
class PrinterFactory{//创建这个类来解决问题
public static Printer getPrinter(int flag){
Printer printer = null;
if(flag == 0){
printer = new HpPrinter();
}else if (flag == 1){
printer = new CannoPrinter();
}
return printer;
}
}
class Test{
public static void main(String args[]){
Printer printer = null;
int flag = 1;
printer = PrinterFactory.getPrinter(flag);
printer.open();
printer.print("test");
printer.close();
}
}
这样就会很容易的添加或删除一个打印机设备了。只需要修改Test类中的flag,并添加一个打印机类即可