学习型 ASP/PHP/ASP.NET 主机 30元/年全能 ASP/PHP/ASP.NET 主机,支持月付专业 MSSQL 数据库空间,支持月付专业 MySQL 数据库空间,支持月付
发新话题
打印

这算工厂模式吗?

这算工厂模式吗?

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);
        }
    }
}
那为高人能讲讲我这段代码算工厂模式吗?

TOP

是。。。。。。。。。。。

TOP

工厂模式和三层架构有那些不同啊!!
我不是一个随便的人,我随便起来不是人我哦。信不?

TOP

发新话题