歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java的工廠設計模式實例

Java的工廠設計模式實例

日期:2017/3/1 9:16:09   编辑:Linux編程

Java的工廠設計模式實例

/*
*工廠類實例
*通過一個工廠類實現生產水果這個特征的對象
*/
interface Fruit{//水果接口
public void eat();
}

class Apple implements Fruit{//蘋果類
public void eat(){
System.out.println("這個水果是個蘋果!");
}
}

class Orange implements Fruit{//橘子類
public void eat(){
System.out.println("這個水果是個橘子!");
}
}

class Factory{//工廠生產對象實例

public static Fruit getInstance(String fruit_name){

Fruit f = null;

if("apple".equals(fruit_name)){
f = new Apple();
}

if("orange".equals(fruit_name)){
f = new Orange();
}
return f;
}

}

public class Factory_test{

public static void main(String args[]){
Fruit f = null;
f = Factory.getInstance(args[0]);//通過外部輸入參數訪問,如java Factory_test apple

if(f!=null){
f.eat();
}

}

}

Copyright © Linux教程網 All Rights Reserved