工厂设计模式

来源:互联网 发布:形容不出门知天下事 编辑:程序博客网 时间:2024/06/05 08:13
interface Fruit{
public void eat();
}


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


class Orange implements 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 Test {


public static void main(String[] args) {


Fruit f = null;
f = Factory.getInstance("apple");
f.eat();

}


}


运行结果:

吃苹果

0 0