工厂设计模式

例子:

interface Fruit{
    public void eat();
}

class Apple interface Fruit{
    public void eat(){
        System.out.println("**吃苹果");
    }
};

class Orange interface Fruit{
    public void eat(){
        System.out.println("**吃桔子");
    }
};

class Factory{
    public static Fruit getInstance(String className){
        Fruit f = null;
        if("apple".equals(className)){
            f = new Apple();
        }
        if("orange".equals(className)){
            f = new Orange();
        }
        return f;
    }
}

public class Factory{
    public static void main(String args[]){
        Fruit f = null;
        f= Factory.getInstance(args[0]);
        if(f!=null){
            f.eat();
        }
    }
}

 

posted on 2015-11-22 15:34  james-roger  阅读(137)  评论(0编辑  收藏  举报