注册 登录
编程论坛 J2EE论坛

这算工厂模式吗?

koman 发布于 2008-04-18 01:55, 945 次点击
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);
        }
    }
}
那为高人能讲讲我这段代码算工厂模式吗?
1 回复
#2
roemin2010-01-25 11:18
基本上像简单工厂模式。
1