| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 937 人关注过本帖
标题:这算工厂模式吗?
只看楼主 加入收藏
koman
Rank: 1
等 级:新手上路
帖 子:71
专家分:0
注 册:2007-9-12
收藏
 问题点数:0 回复次数:1 
这算工厂模式吗?
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:55
roemin
Rank: 1
等 级:新手上路
帖 子:17
专家分:0
注 册:2010-1-24
收藏
得分:0 
基本上像简单工厂模式。
2010-01-25 11:18
快速回复:这算工厂模式吗?
数据加载中...
 
   



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

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