工厂模式在接口与子类之间加入一个过渡端,通过此端口实例化对象,一般成这个过渡端为工厂类

interface Fruit{//水果接口
    public void eat();//抽象吃方法
}
class Orange implements Fruit{//橙子实现水果接口
    public void eat(){
        System.out.println("吃橙子");//实现吃橙子方法
    }
}
class Apple implements Fruit{//苹果实现水果接口
    public void eat(){
        System.out.println("吃苹果");
    }
}
class Factory {
    public static Fruit judgeFruit(String className){
        Fruit f = null;
        if("apple".equals(className)){
            f = new Apple();
        }
        if("orange").equals(className){
            f = new Orange();
        }
        return f;
    }
}
public class TestFactory{
    public static void main(String[] args){
        Fruit f = null;
        f=new Factory.judgeFruit("apple");
        f.eat();
    }
}

 

posted on 2020-07-07 22:06  AlexLiuF  阅读(211)  评论(0编辑  收藏  举报