工厂模式在java中也是经常见得到,工厂模式常常用来在用在解耦合上
package com.factory;
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 Facatory {
public static void main(String[] args) {
Fruit f=Factory.getInstance("apple");
f.eat();
}
}