标题:这算工厂模式吗?
只看楼主
koman
Rank: 1
等 级:新手上路
帖 子:71
专家分:0
注 册:2007-9-12
 问题点数:0 回复次数:2 
这算工厂模式吗?
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 苹果 
2008-04-18 01:45
huwangvs
Rank: 7Rank: 7Rank: 7
等 级:贵宾
威 望:34
帖 子:764
专家分:0
注 册:2007-2-4
得分:0 
是。。。。。。。。。。。
2008-04-18 12:56
恋轩念伊人
Rank: 5Rank: 5
来 自:湖南衡阳
等 级:贵宾
威 望:19
帖 子:643
专家分:0
注 册:2008-2-23
得分:0 
工厂模式和三层架构有那些不同啊!!

我不是一个随便的人,我随便起来不是人我哦。信不?
2008-04-20 10:49



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-209675-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.480132 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved