观察代码1:
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("吃橘子。");
}
};
public class CaseDemo05 {
public static void main(String args[]) {
Fruit f = new Orange();
f.eat();
}
};
观察以上代码中存在的问题。
现在的程序中可以发现,在主方法(客户端)上,是通过关键字new 直接为接口进行实例化,也就是说以后在使用
的时候如果要不更改主方法的话,则主方法中永远只能使用一个类,这样的耦合度太深了。
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 = Factory.getInstance(args[0]);
f.eat();
}
};
此时,中间加入了一个过渡端(Factory),那么都通过过渡端找到接口的实例,这样的设计称为工厂设计,以后扩充子类的时候修改工厂即可:即:某一局部的修改不影响其他环境。