这算工厂模式吗?
import java.util.*;enum FruitName{
Apple,
Banana,
Pear,
Strawberry
}
interface Fruit{
void setWeight(int i);
}
interface Factory{
Fruit getFruit(FruitName name);
}
class Apple implements Fruit{
int weight;
public void setWeight(int weight){
this.weight=weight;
}
public String toString(){
return "这个苹果的重量为:"+this.weight;
}
}
class Banana implements Fruit{
int weight;
public void setWeight(int weight){
this.weight=weight;
}
public String toString(){
return "这个香蕉的重量为:"+this.weight;
}
}
class Pear implements Fruit{
int weight;
public void setWeight(int weight){
this.weight=weight;
}
public String toString(){
return "这个梨子的重量为:"+this.weight;
}
}
class Strawberry implements Fruit{
int weight;
public void setWeight(int weight){
this.weight=weight;
}
public String toString(){
return "这个草莓的重量为:"+this.weight;
}
}
abstract class FruitFactory implements Factory{
private final static FruitFactory f=new FruitFactory(){};
public static FruitFactory getFruitFactory(){
return f;
}
public Fruit getFruit(FruitName name){
Fruit f=null;
try{
f=(Fruit)Class.forName(name.toString()).newInstance();
}catch(Exception ex){
}
return f;
}
}
public class Test {
public Test() {
}
public static void main(String[] args) {
FruitFactory f=FruitFactory.getFruitFactory();
ArrayList<Fruit> list=new ArrayList<Fruit>();
int weight=100;
for(FruitName name : FruitName.values()){
Fruit temp=f.getFruit(name);
temp.setWeight(weight-=5);
list.add(temp);
}
for(Fruit fruit: list){
System.out.println(fruit);
}
}
}
那为高人能讲讲我这段代码算工厂模式吗?