当前位置: 代码迷 >> Java Web开发 >> 这算工厂模式吗?
  详细解决方案

这算工厂模式吗?

热度:270   发布时间:2008-04-18 01:55:18.0
这算工厂模式吗?
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);
        }
    }
}
那为高人能讲讲我这段代码算工厂模式吗?
搜索更多相关主题的帖子: weight  工厂  int  Fruit  苹果  

----------------解决方案--------------------------------------------------------
基本上像简单工厂模式。
----------------解决方案--------------------------------------------------------
  相关解决方案